INT-4453: Move Twitter module to Extensions

JIRA: https://jira.spring.io/browse/INT-4453

Fix typos and language in docs

Fix more typos and language in docs
This commit is contained in:
Artem Bilan
2018-04-23 16:10:18 -04:00
committed by Gary Russell
parent 09d6b76748
commit c6f459c130
64 changed files with 27 additions and 3928 deletions

View File

@@ -47,7 +47,6 @@ allprojects {
'http://docs.spring.io/spring-data-gemfire/docs/current/api/',
'http://docs.spring.io/spring-data/data-mongo/docs/current/api/',
'http://docs.spring.io/spring-data/data-redis/docs/current/api/',
'http://docs.spring.io/spring-social-twitter/docs/current/apidocs/',
'http://docs.spring.io/spring-ws/sites/2.0/apidocs/'
] as String[]
@@ -137,7 +136,6 @@ subprojects { subproject ->
springDataRedisVersion = '2.1.0.BUILD-SNAPSHOT'
springGemfireVersion = '2.1.0.BUILD-SNAPSHOT'
springSecurityVersion = '5.1.0.BUILD-SNAPSHOT'
springSocialTwitterVersion = '1.1.2.RELEASE'
springRetryVersion = '1.2.2.RELEASE'
springVersion = project.hasProperty('springVersion') ? project.springVersion : '5.1.0.BUILD-SNAPSHOT'
springWsVersion = '3.0.1.RELEASE'
@@ -626,26 +624,6 @@ project('spring-integration-test') {
}
}
project('spring-integration-twitter') {
description = 'Spring Integration Twitter Support'
dependencies {
compile project(":spring-integration-core")
compile "org.springframework:spring-web:$springVersion"
compile("org.springframework.social:spring-social-twitter:$springSocialTwitterVersion") {
exclude group: 'org.springframework', module: 'spring-beans'
exclude group: 'org.springframework', module: 'spring-context'
exclude group: 'org.springframework', module: 'spring-core'
exclude group: 'org.springframework', module: 'spring-expression'
exclude group: 'org.springframework', module: 'spring-web'
exclude group: 'org.springframework', module: 'spring-webmvc'
}
compile("javax.activation:activation:$javaxActivationVersion", optional)
testCompile project(":spring-integration-redis")
testCompile project(":spring-integration-redis").sourceSets.test.output
testCompile "io.lettuce:lettuce-core:$lettuceVersion"
}
}
project('spring-integration-webflux') {
description = 'Spring Integration HTTP Support'
dependencies {

View File

@@ -1,75 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.config;
import org.w3c.dom.Element;
import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.xml.AbstractPollingInboundChannelAdapterParser;
import org.springframework.integration.config.xml.IntegrationNamespaceUtils;
import org.springframework.integration.twitter.inbound.DirectMessageReceivingMessageSource;
import org.springframework.integration.twitter.inbound.MentionsReceivingMessageSource;
import org.springframework.integration.twitter.inbound.SearchReceivingMessageSource;
import org.springframework.integration.twitter.inbound.TimelineReceivingMessageSource;
/**
* Parser for inbound Twitter Channel Adapters.
*
* @author Oleg Zhurakousky
* @author Gary Russell
* @since 2.0
*/
public class TwitterInboundChannelAdapterParser extends AbstractPollingInboundChannelAdapterParser {
@Override
protected BeanMetadataElement parseSource(Element element, ParserContext parserContext) {
Class<?> clazz = determineClass(element, parserContext);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(clazz);
builder.addConstructorArgReference(element.getAttribute("twitter-template"));
builder.addConstructorArgValue(element.getAttribute(ID_ATTRIBUTE));
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "query");
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "page-size");
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "metadata-store");
return builder.getBeanDefinition();
}
private static Class<?> determineClass(Element element, ParserContext parserContext) {
Class<?> clazz = null;
String elementName = element.getLocalName().trim();
if ("inbound-channel-adapter".equals(elementName)) {
clazz = TimelineReceivingMessageSource.class;
}
else if ("dm-inbound-channel-adapter".equals(elementName)) {
clazz = DirectMessageReceivingMessageSource.class;
}
else if ("mentions-inbound-channel-adapter".equals(elementName)) {
clazz = MentionsReceivingMessageSource.class;
}
else if ("search-inbound-channel-adapter".equals(elementName)) {
clazz = SearchReceivingMessageSource.class;
}
else {
parserContext.getReaderContext().error("element '" + elementName + "' is not supported by this parser.", element);
}
return clazz;
}
}

View File

@@ -1,45 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.config;
import org.springframework.integration.config.xml.AbstractIntegrationNamespaceHandler;
/**
* Namespace handler for the Twitter adapters.
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Gary Russell
* @since 2.0
*/
public class TwitterNamespaceHandler extends AbstractIntegrationNamespaceHandler {
@Override
public void init() {
// inbound
registerBeanDefinitionParser("inbound-channel-adapter", new TwitterInboundChannelAdapterParser());
registerBeanDefinitionParser("dm-inbound-channel-adapter", new TwitterInboundChannelAdapterParser());
registerBeanDefinitionParser("mentions-inbound-channel-adapter", new TwitterInboundChannelAdapterParser());
registerBeanDefinitionParser("search-inbound-channel-adapter", new TwitterInboundChannelAdapterParser());
// outbound
registerBeanDefinitionParser("outbound-channel-adapter", new TwitterOutboundChannelAdapterParser());
registerBeanDefinitionParser("dm-outbound-channel-adapter", new TwitterOutboundChannelAdapterParser());
registerBeanDefinitionParser("search-outbound-gateway", new TwitterSearchOutboundGatewayParser());
}
}

View File

@@ -1,71 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.ExpressionFactoryBean;
import org.springframework.integration.config.xml.AbstractOutboundChannelAdapterParser;
import org.springframework.integration.twitter.outbound.DirectMessageSendingMessageHandler;
import org.springframework.integration.twitter.outbound.StatusUpdatingMessageHandler;
import org.springframework.util.StringUtils;
/**
* Parser for all outbound Twitter adapters
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Artem Bilan
* @since 2.0
*/
public class TwitterOutboundChannelAdapterParser extends AbstractOutboundChannelAdapterParser {
@Override
protected AbstractBeanDefinition parseConsumer(Element element, ParserContext parserContext) {
Class<?> clazz = determineClass(element, parserContext);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(clazz);
builder.addConstructorArgReference(element.getAttribute("twitter-template"));
String tweetDataExpression = element.getAttribute("tweet-data-expression");
if (StringUtils.hasText(tweetDataExpression)) {
builder.addPropertyValue("tweetDataExpression",
BeanDefinitionBuilder.genericBeanDefinition(ExpressionFactoryBean.class)
.addConstructorArgValue(tweetDataExpression)
.getBeanDefinition());
}
return builder.getBeanDefinition();
}
private static Class<?> determineClass(Element element, ParserContext parserContext) {
Class<?> clazz = null;
String elementName = element.getLocalName().trim();
if ("outbound-channel-adapter".equals(elementName)) {
clazz = StatusUpdatingMessageHandler.class;
}
else if ("dm-outbound-channel-adapter".equals(elementName)) {
clazz = DirectMessageSendingMessageHandler.class;
}
else {
parserContext.getReaderContext().error("element '" + elementName + "' is not supported by this parser.", element);
}
return clazz;
}
}

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.ExpressionFactoryBean;
import org.springframework.integration.config.xml.AbstractConsumerEndpointParser;
import org.springframework.integration.config.xml.IntegrationNamespaceUtils;
import org.springframework.integration.twitter.outbound.TwitterSearchOutboundGateway;
import org.springframework.util.StringUtils;
/**
* Parser for {@code <int-twitter:search-outbound-gateway/>}.
*
* @author Gary Russell
* @since 4.0
*
*/
public class TwitterSearchOutboundGatewayParser extends AbstractConsumerEndpointParser {
@Override
protected String getInputChannelAttributeName() {
return "request-channel";
}
@Override
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(TwitterSearchOutboundGateway.class);
builder.addConstructorArgReference(element.getAttribute("twitter-template"));
String searchArgsExpression = element.getAttribute("search-args-expression");
if (StringUtils.hasText(searchArgsExpression)) {
BeanDefinition expressionDef = new RootBeanDefinition(ExpressionFactoryBean.class);
expressionDef.getConstructorArgumentValues().addGenericArgumentValue(searchArgsExpression);
builder.addPropertyValue("searchArgsExpression", expressionDef);
}
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel", "outputChannel");
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-timeout", "sendTimeout");
return builder;
}
}

View File

@@ -1,4 +0,0 @@
/**
* Contains parser classes for the Twitter namespace support.
*/
package org.springframework.integration.twitter.config;

View File

@@ -1,37 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.core;
/**
* Header keys used by the various Twitter adapters.
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Gary Russell
* @since 2.0
*/
public final class TwitterHeaders {
private static final String PREFIX = "twitter_";
public static final String DM_TARGET_USER_ID = PREFIX + "dmTargetUserId";
public static final String SEARCH_METADATA = PREFIX + "searchMetadata";
private TwitterHeaders() { }
}

View File

@@ -1,4 +0,0 @@
/**
* Provides classes used across all Twitter components.
*/
package org.springframework.integration.twitter.core;

View File

@@ -1,299 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.Lifecycle;
import org.springframework.integration.context.IntegrationContextUtils;
import org.springframework.integration.context.IntegrationObjectSupport;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.metadata.MetadataStore;
import org.springframework.integration.metadata.SimpleMetadataStore;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.social.twitter.api.DirectMessage;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.UserOperations;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* Abstract class that defines common operations for receiving various types of
* messages when using the Twitter API. This class also handles keeping track of
* the latest inbound message it has received and avoiding, where possible,
* redelivery of duplicate messages. This functionality is enabled using the
* {@link org.springframework.integration.metadata.MetadataStore} strategy.
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Mark Fisher
* @author Gunnar Hillert
* @author Artem Bilan
*
* @since 2.0
*/
@SuppressWarnings("rawtypes")
abstract class AbstractTwitterMessageSource<T> extends IntegrationObjectSupport implements MessageSource,
Lifecycle {
private static final int DEFAULT_PAGE_SIZE = 20;
private final Twitter twitter;
private final TweetComparator tweetComparator = new TweetComparator();
private final Object lastEnqueuedIdMonitor = new Object();
private final String metadataKey;
private final Queue<T> tweets = new LinkedBlockingQueue<T>();
private volatile MetadataStore metadataStore;
private volatile int prefetchThreshold = 0;
private volatile long lastEnqueuedId = -1;
private volatile long lastProcessedId = -1;
private volatile int pageSize = DEFAULT_PAGE_SIZE;
private volatile boolean running;
protected AbstractTwitterMessageSource(Twitter twitter, String metadataKey) {
Assert.notNull(twitter, "twitter must not be null");
Assert.notNull(metadataKey, "metadataKey must not be null");
this.twitter = twitter;
if (this.twitter.isAuthorized()) {
UserOperations userOperations = this.twitter.userOperations();
metadataKey += "." + userOperations.getProfileId();
}
this.metadataKey = metadataKey;
}
public void setMetadataStore(MetadataStore metadataStore) {
this.metadataStore = metadataStore;
}
public void setPrefetchThreshold(int prefetchThreshold) {
this.prefetchThreshold = prefetchThreshold;
}
protected Twitter getTwitter() {
return this.twitter;
}
protected int getPageSize() {
return this.pageSize;
}
/**
* Set the limit for the number of results returned on each poll; default 20.
* @param pageSize The pageSize.
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
@Override
protected void onInit() throws Exception {
super.onInit();
if (this.metadataStore == null) {
// first try to look for a 'metadataStore' in the context
BeanFactory beanFactory = this.getBeanFactory();
if (beanFactory != null) {
this.metadataStore = IntegrationContextUtils.getMetadataStore(beanFactory);
}
if (this.metadataStore == null) {
this.metadataStore = new SimpleMetadataStore();
}
}
}
@Override
public synchronized void start() {
if (!this.running) {
String lastId = this.metadataStore.get(this.metadataKey);
// initialize the last status ID from the metadataStore
if (StringUtils.hasText(lastId)) {
this.lastProcessedId = Long.parseLong(lastId);
synchronized (this.lastEnqueuedIdMonitor) {
this.lastEnqueuedId = this.lastProcessedId;
}
}
this.running = true;
}
}
@Override
public synchronized void stop() {
this.running = false;
}
@Override
public synchronized boolean isRunning() {
return this.running;
}
@Override
public Message<?> receive() {
T tweet = this.tweets.poll();
if (tweet == null) {
this.refreshTweetQueueIfNecessary();
tweet = this.tweets.poll();
}
if (tweet != null) {
this.lastProcessedId = this.getIdForTweet(tweet);
this.metadataStore.put(this.metadataKey, String.valueOf(this.lastProcessedId));
return this.getMessageBuilderFactory().withPayload(tweet).build();
}
return null;
}
private void enqueueAll(List<T> tweets) {
Collections.sort(tweets, this.tweetComparator);
for (T tweet : tweets) {
enqueue(tweet);
}
}
private void enqueue(T tweet) {
synchronized (this.lastEnqueuedIdMonitor) {
long id = this.getIdForTweet(tweet);
if (id > this.lastEnqueuedId) {
this.tweets.add(tweet);
synchronized (this.lastEnqueuedIdMonitor) {
this.lastEnqueuedId = id;
}
}
}
}
private void refreshTweetQueueIfNecessary() {
try {
if (this.tweets.size() <= this.prefetchThreshold) {
synchronized (this.lastEnqueuedIdMonitor) {
List<T> tweets = pollForTweets(this.lastEnqueuedId);
if (!CollectionUtils.isEmpty(tweets)) {
enqueueAll(tweets);
}
}
}
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new MessagingException("failed while polling Twitter", e);
}
}
/**
* Subclasses must implement this to return tweets.
* The 'sinceId' value will be negative if no last id is known.
*
* @param sinceId The id of the last reported tweet.
* @return The list of tweets.
*/
protected abstract List<T> pollForTweets(long sinceId);
private long getIdForTweet(T twitterMessage) {
if (twitterMessage instanceof Tweet) {
return ((Tweet) twitterMessage).getId();
}
else if (twitterMessage instanceof DirectMessage) {
return ((DirectMessage) twitterMessage).getId();
}
else {
throw new IllegalArgumentException("Unsupported Twitter object: " + twitterMessage);
}
}
/**
* Remove the metadata key and the corresponding value from the Metadata Store.
*/
@ManagedOperation(description = "Remove the metadata key and the corresponding value from the Metadata Store.")
void resetMetadataStore() {
synchronized (this) {
this.metadataStore.remove(this.metadataKey);
this.lastProcessedId = -1L;
synchronized (this.lastEnqueuedIdMonitor) {
this.lastEnqueuedId = -1L;
}
}
}
/**
*
* @return {@code -1} if lastProcessedId is not set, yet.
*/
@ManagedAttribute
public long getLastProcessedId() {
return this.lastProcessedId;
}
private class TweetComparator implements Comparator<T> {
TweetComparator() {
super();
}
@Override
public int compare(T tweet1, T tweet2) {
// hopefully temporary logic. Will suggest that SpringSocial use a common base class for DM and Tweet
if (tweet1 instanceof Tweet && tweet2 instanceof Tweet) {
Tweet t1 = (Tweet) tweet1;
Tweet t2 = (Tweet) tweet2;
Date t1CreatedAt = t1.getCreatedAt();
Date t2CreatedAt = t2.getCreatedAt();
Assert.notNull(t1CreatedAt, "Tweet is missing 'createdAt' date. Cannot compare.");
Assert.notNull(t2CreatedAt, "Tweet is missing 'createdAt' date. Cannot compare.");
return t1CreatedAt.compareTo(t2CreatedAt);
}
else if (tweet1 instanceof DirectMessage && tweet2 instanceof DirectMessage) {
DirectMessage d1 = (DirectMessage) tweet1;
DirectMessage d2 = (DirectMessage) tweet2;
Date d1CreatedAt = d1.getCreatedAt();
Date d2CreatedAt = d2.getCreatedAt();
Assert.notNull(d1CreatedAt, "DirectMessage is missing 'createdAt' date. Cannot compare.");
Assert.notNull(d2CreatedAt, "DirectMessage is missing 'createdAt' date. Cannot compare.");
return d1CreatedAt.compareTo(d2CreatedAt);
}
else {
throw new IllegalArgumentException("Uncomparable Twitter objects: " + tweet1 + " and " + tweet2);
}
}
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import java.util.List;
import org.springframework.social.twitter.api.DirectMessage;
import org.springframework.social.twitter.api.Twitter;
/**
* This class handles support for receiving DMs (direct messages) using Twitter.
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Mark Fisher
* @author Gary Russell
* @since 2.0
*/
public class DirectMessageReceivingMessageSource extends AbstractTwitterMessageSource<DirectMessage> {
public DirectMessageReceivingMessageSource(Twitter twitter, String metadataKey) {
super(twitter, metadataKey);
}
@Override
public String getComponentType() {
return "twitter:dm-inbound-channel-adapter";
}
@Override
protected List<DirectMessage> pollForTweets(long sinceId) {
return this.getTwitter().directMessageOperations().getDirectMessagesReceived(1, this.getPageSize(), sinceId, 0);
}
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import java.util.List;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
/**
* Receives Message Tweets
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Gary Russell
* @since 2.0
*/
public class MentionsReceivingMessageSource extends AbstractTwitterMessageSource<Tweet> {
public MentionsReceivingMessageSource(Twitter twitter, String metadataKey) {
super(twitter, metadataKey);
}
@Override
public String getComponentType() {
return "twitter:mentions-inbound-channel-adapter";
}
@Override
protected List<Tweet> pollForTweets(long sinceId) {
return this.getTwitter().timelineOperations().getMentions(this.getPageSize(), sinceId, 0);
}
}

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import java.util.Collections;
import java.util.List;
import org.springframework.social.twitter.api.SearchParameters;
import org.springframework.social.twitter.api.SearchResults;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.util.Assert;
/**
* @author Oleg Zhurakousky
* @author Mark Fisher
* @author Gunnar Hillert
* @author Gary Russell
* @since 2.0
*/
public class SearchReceivingMessageSource extends AbstractTwitterMessageSource<Tweet> {
private volatile String query;
public SearchReceivingMessageSource(Twitter twitter, String metadataKey) {
super(twitter, metadataKey);
}
public void setQuery(String query) {
Assert.hasText(query, "'query' must not be null");
this.query = query;
}
@Override
public String getComponentType() {
return "twitter:search-inbound-channel-adapter";
}
@Override
protected List<Tweet> pollForTweets(long sinceId) {
SearchParameters searchParameters = new SearchParameters(this.query).count(this.getPageSize()).sinceId(sinceId);
SearchResults results = this.getTwitter().searchOperations().search(searchParameters);
return (results != null) ? results.getTweets() : Collections.<Tweet>emptyList();
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import java.util.List;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
/**
* This {@link org.springframework.integration.core.MessageSource} lets Spring Integration consume
* given account's timeline as messages. It has support for dynamic throttling of API requests.
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Gary Russell
* @since 2.0
*/
public class TimelineReceivingMessageSource extends AbstractTwitterMessageSource<Tweet> {
public TimelineReceivingMessageSource(Twitter twitter, String metadataKey) {
super(twitter, metadataKey);
}
@Override
public String getComponentType() {
return "twitter:inbound-channel-adapter";
}
@Override
protected List<Tweet> pollForTweets(long sinceId) {
return this.getTwitter().timelineOperations().getHomeTimeline(this.getPageSize(), sinceId, 0);
}
}

View File

@@ -1,4 +0,0 @@
/**
* Provides inbound Twitter components.
*/
package org.springframework.integration.twitter.inbound;

View File

@@ -1,65 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.outbound;
import org.springframework.integration.handler.AbstractMessageHandler;
import org.springframework.integration.twitter.core.TwitterHeaders;
import org.springframework.messaging.Message;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.util.Assert;
/**
* Simple adapter to support sending outbound direct messages ("DM"s) using Twitter.
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Mark Fisher
* @since 2.0
*/
public class DirectMessageSendingMessageHandler extends AbstractMessageHandler {
private final Twitter twitter;
public DirectMessageSendingMessageHandler(Twitter twitter) {
Assert.notNull(twitter, "twitter must not be null");
this.twitter = twitter;
}
@Override
public String getComponentType() {
return "twitter:dm-outbound-channel-adapter";
}
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
Assert.isTrue(message.getPayload() instanceof String, "Only payload of type String is supported. " +
"Consider adding a transformer to the message flow in front of this adapter.");
Object toUser = message.getHeaders().get(TwitterHeaders.DM_TARGET_USER_ID);
Assert.isTrue(toUser instanceof String || toUser instanceof Number,
"the header '" + TwitterHeaders.DM_TARGET_USER_ID +
"' must contain either a String (a screenname) or an number (a user ID)");
String payload = (String) message.getPayload();
if (toUser instanceof Number) {
this.twitter.directMessageOperations().sendDirectMessage(((Number) toUser).longValue(), payload);
}
else if (toUser instanceof String) {
this.twitter.directMessageOperations().sendDirectMessage((String) toUser, payload);
}
}
}

View File

@@ -1,121 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.outbound;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.TypeLocator;
import org.springframework.expression.spel.support.StandardTypeLocator;
import org.springframework.integration.expression.ExpressionUtils;
import org.springframework.integration.handler.AbstractMessageHandler;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.TweetData;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.util.Assert;
/**
* MessageHandler for sending regular status updates as well as 'replies' or 'mentions'.
*
* @author Josh Long
* @author Oleg Zhurakousky
* @author Artem Bilan
* @since 2.0
*/
public class StatusUpdatingMessageHandler extends AbstractMessageHandler {
private final Twitter twitter;
private volatile Expression tweetDataExpression;
private EvaluationContext evaluationContext;
public StatusUpdatingMessageHandler(Twitter twitter) {
Assert.notNull(twitter, "twitter must not be null");
this.twitter = twitter;
}
@Override
public String getComponentType() {
return "twitter:outbound-channel-adapter";
}
/**
* An expression that is used to build the {@link TweetData}; must resolve to a
* {@link TweetData} object, or a {@link String}, or a {@link Tweet}.
* <p> When using a {@code TweetData} directly in the expression, it is not necessary
* to include the package:
* {@code "new TweetData("test").withMedia(headers.mediaResource).displayCoordinates(true)")}.
* @param tweetDataExpression The expression.
* @since 4.0
*/
public void setTweetDataExpression(Expression tweetDataExpression) {
this.tweetDataExpression = tweetDataExpression;
}
public void setIntegrationEvaluationContext(EvaluationContext evaluationContext) {
this.evaluationContext = evaluationContext;
}
@Override
protected void onInit() throws Exception {
super.onInit();
if (this.evaluationContext == null) {
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
TypeLocator typeLocator = this.evaluationContext.getTypeLocator();
if (typeLocator instanceof StandardTypeLocator) {
/*
* Register the twitter api package so they don't need a FQCN for TweetData.
*/
((StandardTypeLocator) typeLocator).registerImport("org.springframework.social.twitter.api");
}
}
}
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
Object value;
if (this.tweetDataExpression != null) {
value = this.tweetDataExpression.getValue(this.evaluationContext, message);
}
else {
value = message.getPayload();
}
Assert.notNull(value, "The tweetData cannot evaluate to 'null'.");
TweetData tweetData = null;
if (value instanceof TweetData) {
tweetData = (TweetData) value;
}
else if (value instanceof Tweet) {
tweetData = new TweetData(((Tweet) value).getText());
}
else if (value instanceof String) {
tweetData = new TweetData((String) value);
}
else {
throw new MessageHandlingException(message, "Unsupported tweetData: " + value);
}
this.twitter.timelineOperations().updateStatus(tweetData);
}
}

View File

@@ -1,161 +0,0 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.outbound;
import java.util.Collections;
import java.util.List;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.TypeLocator;
import org.springframework.expression.spel.support.StandardTypeLocator;
import org.springframework.integration.expression.ExpressionUtils;
import org.springframework.integration.handler.AbstractReplyProducingMessageHandler;
import org.springframework.integration.twitter.core.TwitterHeaders;
import org.springframework.messaging.Message;
import org.springframework.social.twitter.api.SearchParameters;
import org.springframework.social.twitter.api.SearchResults;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.util.Assert;
/**
* The {@link AbstractReplyProducingMessageHandler} implementation to perform request/reply
* Twitter search with {@link SearchParameters} as the result of {@link #searchArgsExpression}
* expression evaluation.
*
* @author Gary Russell
* @since 4.0
*/
public class TwitterSearchOutboundGateway extends AbstractReplyProducingMessageHandler {
private static final int DEFAULT_PAGE_SIZE = 20;
private final Twitter twitter;
private volatile Expression searchArgsExpression;
private volatile EvaluationContext evaluationContext;
public TwitterSearchOutboundGateway(Twitter twitter) {
Assert.notNull(twitter, "'twitter' must not be null");
this.twitter = twitter;
}
/**
* An expression that is used to build the search; must resolve to a
* {@code SearchParameters} object, or a
* {@link String}, in which case the default page size of 20 is applied,
* or a list of up to 4 arguments, such as
* {@code "{payload, headers.pageSize, headers.sinceId, headers.maxId}"}.
* The first (required) argument must resolve to a String (query), the
* optional arguments must resolve to an Number and represent the
* page size, sinceId, and maxId respectively. Refer to the 'Spring
* Social Twitter' documentation for more details.
* <p> When using a {@code SearchParameters} directly, it is not necessary
* to include the package: {@code "new SearchParameters("#foo").count(20)")}.
* <p> Default: {@code "payload"}.
* @param searchArgsExpression The expression.
*/
public void setSearchArgsExpression(Expression searchArgsExpression) {
Assert.notNull(searchArgsExpression, "'searchArgsExpression' must not be null");
this.searchArgsExpression = searchArgsExpression;
}
public void setIntegrationEvaluationContext(EvaluationContext evaluationContext) {
this.evaluationContext = evaluationContext;
}
@Override
public String getComponentType() {
return "twitter:search-outbound-gateway";
}
protected Twitter getTwitter() {
return this.twitter;
}
@Override
protected void doInit() {
super.doInit();
if (this.evaluationContext == null) {
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
TypeLocator typeLocator = this.evaluationContext.getTypeLocator();
if (typeLocator instanceof StandardTypeLocator) {
/*
* Register the twitter api package so they don't need a FQCN for SearchParameters.
*/
((StandardTypeLocator) typeLocator).registerImport("org.springframework.social.twitter.api");
}
}
}
@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
Object args;
if (this.searchArgsExpression != null) {
args = this.searchArgsExpression.getValue(this.evaluationContext, requestMessage);
}
else {
args = requestMessage.getPayload();
}
Assert.notNull(args, "The twitter search expression cannot evaluate to 'null'.");
SearchParameters searchParameters;
if (args instanceof SearchParameters) {
searchParameters = (SearchParameters) args;
}
else if (args instanceof String) {
searchParameters = new SearchParameters((String) args).count(DEFAULT_PAGE_SIZE);
}
else if (args instanceof List) {
List<?> list = (List<?>) args;
Assert.isTrue(list.size() > 0 && list.size() < 5, "Between 1 and 4 search arguments are required");
Assert.isInstanceOf(String.class, list.get(0), "The first search argument (query) must be a String");
searchParameters = new SearchParameters((String) list.get(0));
if (list.size() > 1) {
Assert.isInstanceOf(Number.class, list.get(1),
"The second search argument (pageSize) must be a Number");
searchParameters.count(((Number) list.get(1)).intValue());
if (list.size() > 2) {
Assert.isInstanceOf(Number.class, list.get(2),
"The third search argument (sinceId) must be a Number");
searchParameters.sinceId(((Number) list.get(2)).longValue());
}
if (list.size() > 3) {
Assert.isInstanceOf(Number.class, list.get(3),
"The fourth search argument (maxId) must be a Number");
searchParameters.maxId(((Number) list.get(3)).longValue());
}
}
}
else {
throw new IllegalArgumentException(
"Search Expression must evaluate to a 'SearchParameters', 'String' or 'List'.");
}
SearchResults results = this.getTwitter().searchOperations().search(searchParameters);
if (results != null) {
List<Tweet> tweets = (results.getTweets() != null ? results.getTweets() : Collections.<Tweet>emptyList());
return this.getMessageBuilderFactory().withPayload(tweets)
.setHeader(TwitterHeaders.SEARCH_METADATA, results.getSearchMetadata());
}
else {
return null;
}
}
}

View File

@@ -1,4 +0,0 @@
/**
* Provides outbound Twitter components.
*/
package org.springframework.integration.twitter.outbound;

View File

@@ -1,2 +0,0 @@
http\://www.springframework.org/schema/integration/twitter=org.springframework.integration.twitter.config.TwitterNamespaceHandler

View File

@@ -1,2 +0,0 @@
http\://www.springframework.org/schema/integration/twitter/spring-integration-twitter-5.1.xsd=org/springframework/integration/twitter/config/spring-integration-twitter-5.1.xsd
http\://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd=org/springframework/integration/twitter/config/spring-integration-twitter-5.1.xsd

View File

@@ -1,4 +0,0 @@
# Tooling related information for the integration twitter namespace
http\://www.springframework.org/schema/integration/twitter@name=integration twitter Namespace
http\://www.springframework.org/schema/integration/twitter@prefix=int-twitter
http\://www.springframework.org/schema/integration/twitter@icon=org/springframework/integration/twitter/config/spring-integration-twitter.gif

View File

@@ -1,322 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.springframework.org/schema/integration/twitter"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:integration="http://www.springframework.org/schema/integration"
targetNamespace="http://www.springframework.org/schema/integration/twitter"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:import namespace="http://www.springframework.org/schema/beans"/>
<xsd:import namespace="http://www.springframework.org/schema/tool"/>
<xsd:import namespace="http://www.springframework.org/schema/integration"
schemaLocation="http://www.springframework.org/schema/integration/spring-integration-5.1.xsd"/>
<!--
INBOUND
-->
<xsd:element name="inbound-channel-adapter">
<xsd:annotation>
<xsd:documentation>
Defines a Polling Channel Adapter for the
'org.springframework.integration.twitter.inbound.TimelineReceivingMessageSource' that consumes your
friends' timeline updates from Twitter and sends Messages whose payloads are Tweet objects.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType >
<xsd:complexContent>
<xsd:extension base="inbound-twitter-type"/>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="mentions-inbound-channel-adapter">
<xsd:annotation>
<xsd:documentation>
Defines a Polling Channel Adapter for the
'org.springframework.integration.twitter.inbound.MentionsReceivingMessageSource' that consumes mentions
of your handle from Twitter and sends Messages whose payloads are Tweet objects.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="inbound-twitter-type"/>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="search-inbound-channel-adapter">
<xsd:annotation>
<xsd:documentation>
Defines a Polling Channel Adapter for the
'org.springframework.integration.twitter.inbound.SearchReceivingMessageSource' that consumes search
results for a given query from Twitter and sends Messages whose payloads are Tweet objects.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="inbound-twitter-type">
<xsd:attribute name="query" type="xsd:string" use="required">
<xsd:annotation>
<xsd:documentation>
Twitter search query (e.g, #springintegration).
For more info on Twitter queries please refer to this site: http://search.twitter.com/operators)
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="dm-inbound-channel-adapter">
<xsd:annotation>
<xsd:documentation>
Defines a Polling Channel Adapter for the
'org.springframework.integration.twitter.inbound.DirectMessageReceivingMessageSource' that consumes
direct messages from Twitter and sends Messages whose payloads are DirectMessage objects.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="inbound-twitter-type"/>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<!--
OUTBOUND
-->
<xsd:element name="dm-outbound-channel-adapter">
<xsd:annotation>
<xsd:documentation>
Configures a Consumer Endpoint for the
'org.springframework.integration.twitter.outbound.DirectMessageSendingMessageHandler'
that sends Direct Messages to a Twitter user as
specified in the header whose name is defined by the TwitterHeaders.DM_TARGET_USER_ID constant.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="outbound-twitter-type">
<xsd:attributeGroup ref="integration:channelAdapterAttributes"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="outbound-channel-adapter">
<xsd:annotation>
<xsd:documentation>
Configures a Consumer Endpoint for the
'org.springframework.integration.twitter.outbound.StatusUpdatingMessageHandler'
that posts a status update to the authorized user's timeline.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="outbound-twitter-type">
<xsd:attribute name="tweet-data-expression" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
A SpEL expression that evaluates to tweetData; the evaluation result type can be
an 'org.springframework.social.twitter.api.TweetData', a 'String' or
'org.springframework.social.twitter.api.Tweet'.
Default: "payload".
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attributeGroup ref="integration:channelAdapterAttributes"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<xsd:element name="search-outbound-gateway">
<xsd:annotation>
<xsd:documentation><![CDATA[
Configures a Consumer Endpoint for the
'org.springframework.integration.twitter.outbound.TwitterSearchOutboundGateway'
that issues Twitter searches and produces their results.
]]></xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="outbound-twitter-type">
<xsd:attribute name="id" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
The bean id of this gateway; the MessageHandler is also registered with this id
plus a suffix '.handler'.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="search-args-expression" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
A SpEL expression that evaluates to search arguments; the evaluation result type can be
an 'org.springframework.social.twitter.api.SearchParameters', a 'String', in
which case the default page size of 20 is used, or the expression can evaluate to
a list of search
arguments, for example: "{payload, headers.pageSize, headers.sinceId, headers.maxId}".
Default: "payload".
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="request-channel" use="required" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type
type="org.springframework.messaging.MessageChannel" />
</tool:annotation>
</xsd:appinfo>
<xsd:documentation>
Identifies the request channel attached to this gateway.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="reply-channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type
type="org.springframework.messaging.MessageChannel" />
</tool:annotation>
</xsd:appinfo>
<xsd:documentation>
Identifies the reply channel attached to this
gateway.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="reply-timeout" type="xsd:string">
<xsd:annotation>
<xsd:documentation><![CDATA[
Allows you to specify how long this gateway will wait for
the reply message to be sent successfully to the reply channel
before throwing an exception. This attribute only applies when the
channel might block, for example when using a bounded queue channel that
is currently full.
Also, keep in mind that when sending to a DirectChannel, the
invocation will occur in the sender's thread. Therefore,
the failing of the send operation may be caused by other
components further downstream.
The "reply-timeout" attribute maps to the "sendTimeout" property of the
underlying 'MessagingTemplate' instance (org.springframework.integration.core.MessagingTemplate).
The attribute will default, if not specified, to '-1', meaning that
by default, the Gateway will wait indefinitely. The value is
specified in milliseconds.
]]></xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attributeGroup ref="integration:smartLifeCycleAttributeGroup"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
<!--
BASE TYPES
-->
<xsd:complexType name="inbound-twitter-type">
<xsd:sequence>
<xsd:element ref="integration:poller" minOccurs="0" maxOccurs="1" />
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required">
<xsd:annotation>
<xsd:documentation>
The bean id of this Polling Endpoint; the MessageSource is also registered with this id
plus a suffix '.source'; also used as the
MetaDataStore key with suffix '.' + the profileId from the authorized Twitter user.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.messaging.MessageChannel" />
</tool:annotation>
</xsd:appinfo>
<xsd:documentation>
Identifies the channel the attached to this adapter, to which messages will be sent.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attributeGroup ref="integration:smartLifeCycleAttributeGroup"/>
<xsd:attribute name="twitter-template" type="xsd:string" use="required">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.social.twitter.api.Twitter"/>
</tool:annotation>
</xsd:appinfo>
<xsd:documentation>
Reference to a TwitterTemplate bean provided by the Spring Social project.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="metadata-store" use="optional" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
Reference to a MetadataStore instance for storing metadata associated with
the retrieved feeds. If the implementation is persistent, it can help to
prevent duplicates between restarts. If shared, it can help coordinate multiple
instances of an adapter across different processes.
</xsd:documentation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.integration.metadata.MetadataStore" />
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="page-size" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
Limits the number of tweets retrieved on each poll; default: 20.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
<xsd:complexType name="outbound-twitter-type">
<xsd:choice minOccurs="0" maxOccurs="2">
<xsd:element name="transactional" type="integration:transactionalType" minOccurs="0" maxOccurs="1" />
<xsd:element name="request-handler-advice-chain" type="integration:handlerAdviceChainType"
minOccurs="0" maxOccurs="1" />
<xsd:element ref="integration:poller" minOccurs="0" maxOccurs="1"/>
</xsd:choice>
<xsd:attribute name="twitter-template" use="required" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.social.twitter.api.Twitter"/>
</tool:annotation>
</xsd:appinfo>
<xsd:documentation>
Reference to a TwitterTemplate bean provided by the Spring Social project.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="order">
<xsd:annotation>
<xsd:documentation>
Specifies the order for invocation when this endpoint is connected as a
subscriber to a SubscribableChannel.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
</xsd:schema>

View File

@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<beans:bean id="twitter" class="org.springframework.social.twitter.api.impl.TwitterTemplate"/>
<chain input-channel="inputChannel">
<twitter:outbound-channel-adapter twitter-template="twitter">
<twitter:request-handler-advice-chain>
<beans:bean class="org.springframework.integration.twitter.config.TestSendingMessageHandlerParserTests$FooAdvice" />
</twitter:request-handler-advice-chain>
</twitter:outbound-channel-adapter>
</chain>
</beans:beans>

View File

@@ -1,51 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<beans:bean id="twitter" class="org.mockito.Mockito" factory-method="mock">
<beans:constructor-arg value="org.springframework.social.twitter.api.Twitter"/>
</beans:bean>
<channel id="inbound_mentions"/>
<twitter:mentions-inbound-channel-adapter id="mentionAdapter"
twitter-template="twitter"
channel="inbound_mentions"
page-size="23"
auto-startup="false">
<poller fixed-rate="5000" max-messages-per-poll="3"/>
</twitter:mentions-inbound-channel-adapter>
<twitter:dm-inbound-channel-adapter id="dmAdapter"
twitter-template="twitter"
channel="inbound_mentions"
page-size="45"
auto-startup="false">
<poller fixed-rate="5000" max-messages-per-poll="3"/>
</twitter:dm-inbound-channel-adapter>
<twitter:inbound-channel-adapter id="updateAdapter"
twitter-template="twitter"
channel="inbound_mentions"
page-size="67"
auto-startup="false">
<poller fixed-rate="5000" max-messages-per-poll="3"/>
</twitter:inbound-channel-adapter>
</beans:beans>

View File

@@ -1,83 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.endpoint.SourcePollingChannelAdapter;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.twitter.inbound.DirectMessageReceivingMessageSource;
import org.springframework.integration.twitter.inbound.MentionsReceivingMessageSource;
import org.springframework.integration.twitter.inbound.TimelineReceivingMessageSource;
/**
* @author Oleg Zhurakousky
* @author Gunnar Hillert
* @author Gary Russell
* @author Rijnard van Tonder
*/
public class TestReceivingMessageSourceParserTests {
@Test
public void testReceivingAdapterConfigurationAutoStartup() {
ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
"TestReceivingMessageSourceParser-context.xml", getClass());
SourcePollingChannelAdapter spca = ac.getBean("mentionAdapter", SourcePollingChannelAdapter.class);
MentionsReceivingMessageSource ms = TestUtils.getPropertyValue(spca, "source",
MentionsReceivingMessageSource.class);
assertEquals(Integer.valueOf(23), TestUtils.getPropertyValue(ms, "pageSize", Integer.class));
assertNotNull(ms);
spca = ac.getBean("dmAdapter", SourcePollingChannelAdapter.class);
DirectMessageReceivingMessageSource dms = TestUtils.getPropertyValue(spca, "source",
DirectMessageReceivingMessageSource.class);
assertNotNull(dms);
assertEquals(Integer.valueOf(45), TestUtils.getPropertyValue(dms, "pageSize", Integer.class));
spca = ac.getBean("updateAdapter", SourcePollingChannelAdapter.class);
TimelineReceivingMessageSource tms = TestUtils.getPropertyValue(spca, "source",
TimelineReceivingMessageSource.class);
assertEquals(Integer.valueOf(67), TestUtils.getPropertyValue(tms, "pageSize", Integer.class));
assertNotNull(tms);
ac.close();
}
@Test
public void testThatMessageSourcesAreRegisteredAsBeans() {
ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
"TestReceivingMessageSourceParser-context.xml", this.getClass());
MentionsReceivingMessageSource ms = ac.getBean("mentionAdapter.source", MentionsReceivingMessageSource.class);
assertNotNull(ms);
DirectMessageReceivingMessageSource dms = ac.getBean("dmAdapter.source",
DirectMessageReceivingMessageSource.class);
assertNotNull(dms);
TimelineReceivingMessageSource tms = ac.getBean("updateAdapter.source", TimelineReceivingMessageSource.class);
assertNotNull(tms);
ac.close();
}
}

View File

@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<channel id="searchChannel"/>
<beans:bean id="twitter" class="org.mockito.Mockito" factory-method="mock">
<beans:constructor-arg value="org.springframework.social.twitter.api.Twitter" />
</beans:bean>
<twitter:search-inbound-channel-adapter id="searchAdapterWithTemplate"
channel="searchChannel"
twitter-template="twitter"
page-size="23"
query="#springintegration"
auto-startup="false">
<poller fixed-rate="5000" max-messages-per-poll="3"/>
</twitter:search-inbound-channel-adapter>
</beans:beans>

View File

@@ -1,49 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.endpoint.SourcePollingChannelAdapter;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.twitter.inbound.SearchReceivingMessageSource;
import org.springframework.social.twitter.api.Twitter;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
*/
public class TestSearchReceivingMessageSourceParserTests {
@Test
public void testSearchReceivingDefaultTemplate() {
ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
"TestSearchReceivingMessageSourceParser-context.xml", this.getClass());
SourcePollingChannelAdapter spca = ac.getBean("searchAdapterWithTemplate", SourcePollingChannelAdapter.class);
SearchReceivingMessageSource ms = (SearchReceivingMessageSource) TestUtils.getPropertyValue(spca, "source");
assertEquals(Integer.valueOf(23), TestUtils.getPropertyValue(ms, "pageSize", Integer.class));
Twitter template = (Twitter) TestUtils.getPropertyValue(ms, "twitter");
assertNotNull(template);
ac.close();
}
}

View File

@@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<beans:bean id="twitter" class="org.springframework.social.twitter.api.impl.TwitterTemplate">
<beans:constructor-arg name="clientToken" value="myDummyClientToken"/>
</beans:bean>
<channel id="inbound_mentions"/>
<channel id="inputChannel"/>
<twitter:dm-outbound-channel-adapter id="dmAdapter" order="23"
twitter-template="twitter"
channel="inputChannel"/>
<twitter:outbound-channel-adapter twitter-template="twitter" channel="inputChannel" />
<twitter:dm-outbound-channel-adapter id="dmAdvised" order="23"
twitter-template="twitter"
channel="inputChannel">
<twitter:request-handler-advice-chain>
<beans:bean class="org.springframework.integration.twitter.config.TestSendingMessageHandlerParserTests$FooAdvice" />
</twitter:request-handler-advice-chain>
</twitter:dm-outbound-channel-adapter>
<twitter:outbound-channel-adapter id="advised" twitter-template="twitter" channel="inputChannel">
<twitter:request-handler-advice-chain>
<beans:bean class="org.springframework.integration.twitter.config.TestSendingMessageHandlerParserTests$FooAdvice" />
</twitter:request-handler-advice-chain>
</twitter:outbound-channel-adapter>
</beans:beans>

View File

@@ -1,92 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.twitter.outbound.DirectMessageSendingMessageHandler;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.support.GenericMessage;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Artem Bilan
* @author Gary Russell
* @since 2.0
*/
public class TestSendingMessageHandlerParserTests {
private static volatile int adviceCalled;
@Test
public void testSendingMessageHandlerSuccessfulBootstrap() {
ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
"TestSendingMessageHandlerParser-context.xml", this.getClass());
EventDrivenConsumer dmAdapter = ac.getBean("dmAdapter", EventDrivenConsumer.class);
MessageHandler handler = TestUtils.getPropertyValue(dmAdapter, "handler", MessageHandler.class);
assertEquals(DirectMessageSendingMessageHandler.class, handler.getClass());
assertEquals(23, TestUtils.getPropertyValue(handler, "order"));
dmAdapter = ac.getBean("dmAdvised", EventDrivenConsumer.class);
handler = TestUtils.getPropertyValue(dmAdapter, "handler", MessageHandler.class);
handler.handleMessage(new GenericMessage<String>("foo"));
assertEquals(1, adviceCalled);
MessageHandler handler2 = TestUtils.getPropertyValue(ac.getBean("advised"), "handler", MessageHandler.class);
assertNotSame(handler, handler2);
handler2.handleMessage(new GenericMessage<String>("foo"));
assertEquals(2, adviceCalled);
ac.close();
}
@Test
public void testInt2718FailForOutboundAdapterWithRequestHandlerAdviceChainWithinChainConfig() {
try {
new ClassPathXmlApplicationContext("OutboundAdapterWithRHACWithinChain-fail-context.xml", this.getClass())
.close();
fail("Expected BeanDefinitionParsingException");
}
catch (BeansException e) {
assertTrue(e instanceof BeanDefinitionParsingException);
assertTrue(e.getMessage().contains("'request-handler-advice-chain' isn't allowed " +
"for 'twitter:outbound-channel-adapter' within a <chain/>, because its Handler isn't an AbstractReplyProducingMessageHandler"));
}
}
public static class FooAdvice extends AbstractRequestHandlerAdvice {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
adviceCalled++;
return null;
}
}
}

View File

@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<bean id="tt" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="org.springframework.social.twitter.api.Twitter" />
</bean>
<int:channel id="in" />
<int-twitter:search-outbound-gateway id="defaultTSOG" twitter-template="tt" request-channel="in" />
<int-twitter:search-outbound-gateway id="allAttsTSOG"
request-channel="in"
twitter-template="tt"
search-args-expression="'foo'"
reply-channel="out"
order="23"
reply-timeout="123"
auto-startup="false"
phase="100" />
<int-twitter:search-outbound-gateway id="polledAndAdvisedTSOG" twitter-template="tt" request-channel="out">
<int-twitter:request-handler-advice-chain>
<bean class="org.springframework.integration.handler.advice.RequestHandlerRetryAdvice" />
</int-twitter:request-handler-advice-chain>
<int:poller fixed-rate="1000" />
</int-twitter:search-outbound-gateway>
<int:channel id="out">
<int:queue />
</int:channel>
</beans>

View File

@@ -1,84 +0,0 @@
/*
* Copyright 2014-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.endpoint.PollingConsumer;
import org.springframework.integration.handler.advice.RequestHandlerRetryAdvice;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.twitter.outbound.TwitterSearchOutboundGateway;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Gary Russell
* @author Artem Bilan
*
* @since 4.0
*
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class TwitterSearchOutboundGatewayParserTests {
@Autowired
@Qualifier("defaultTSOG.handler")
private TwitterSearchOutboundGateway defaultTSOG;
@Autowired
@Qualifier("allAttsTSOG.handler")
private TwitterSearchOutboundGateway allAttsTSOG;
@Autowired
private PollingConsumer polledAndAdvisedTSOG;
@Autowired
private Twitter twitter;
@Test
public void testDefault() {
assertSame(twitter, TestUtils.getPropertyValue(defaultTSOG, "twitter"));
}
@Test
public void testAllAtts() {
assertSame(twitter, TestUtils.getPropertyValue(allAttsTSOG, "twitter"));
assertEquals("'foo'", TestUtils.getPropertyValue(allAttsTSOG, "searchArgsExpression.expression"));
}
@Test
public void testAdvised() {
assertSame(twitter, TestUtils.getPropertyValue(polledAndAdvisedTSOG, "handler.twitter"));
assertThat(TestUtils.getPropertyValue(polledAndAdvisedTSOG, "handler.adviceChain", List.class).get(0),
Matchers.instanceOf(RequestHandlerRetryAdvice.class));
}
}

View File

@@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<message-history/>
<context:property-placeholder location="classpath:sample.properties"/>
<channel id="inbound_dm"/>
<channel id="inbound_mentions"/>
<channel id="inbound_updates"/>
<channel id="inbound_search"/>
<beans:bean id="twitterTemplate" class="org.springframework.social.twitter.api.impl.TwitterTemplate">
<beans:constructor-arg value="${twitter.oauth.consumerKey}"/>
<beans:constructor-arg value="${twitter.oauth.consumerSecret}"/>
<beans:constructor-arg value="${twitter.oauth.accessToken}"/>
<beans:constructor-arg value="${twitter.oauth.accessTokenSecret}"/>
</beans:bean>
<!-- <twitter:mentions-inbound-channel-adapter twitter-template="twitterTemplate" channel="inbound_mentions"> -->
<!-- <poller fixed-rate="5000" max-messages-per-poll="-1"/> -->
<!-- </twitter:mentions-inbound-channel-adapter> -->
<!-- <service-activator input-channel="inbound_mentions" ref="twitterAnnouncer" method="mention"/> -->
<!-- <twitter:dm-inbound-channel-adapter twitter-template="twitterTemplate" channel="inbound_dm"> -->
<!-- <poller fixed-rate="5000" max-messages-per-poll="-1"/> -->
<!-- </twitter:dm-inbound-channel-adapter> -->
<!-- <service-activator input-channel="inbound_dm" ref="twitterAnnouncer" method="dm"/> -->
<!-- <twitter:search-inbound-channel-adapter id="searchAdapter" twitter-template="twitterTemplate" channel="inbound_search" query="#springintegration"> -->
<!-- <poller fixed-rate="5000" max-messages-per-poll="5"/> -->
<!-- </twitter:search-inbound-channel-adapter> -->
<!-- <service-activator input-channel="inbound_search" ref="twitterAnnouncer" method="search"/> -->
<twitter:inbound-channel-adapter id="twitterInbound" twitter-template="twitterTemplate" channel="inbound_updates">
<poller fixed-rate="1000" max-messages-per-poll="3"/>
</twitter:inbound-channel-adapter>
<service-activator input-channel="inbound_updates" ref="twitterAnnouncer" method="updates"/>
<beans:bean id="twitterAnnouncer" class="org.springframework.integration.twitter.ignored.TwitterAnnouncer"/>
</beans:beans>

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.ignored;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
*
*/
public class TestReceivingUsingNamespace {
@Test
@Ignore
/*
* In order to run this test you need to provide oauth properties in sample.properties on the classpath.
*/
public void testUpdatesWithRealTwitter() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
ConfigurableApplicationContext ctx =
new ClassPathXmlApplicationContext("TestReceivingUsingNamespace-context.xml", this.getClass());
latch.await(10000, TimeUnit.SECONDS);
ctx.close();
}
}

View File

@@ -1,40 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<message-history/>
<context:property-placeholder location="classpath:sample.properties"/>
<beans:bean id="twitterTemplate" class="org.springframework.social.twitter.api.impl.TwitterTemplate">
<beans:constructor-arg value="${twitter.oauth.consumerKey}"/>
<beans:constructor-arg value="${twitter.oauth.consumerSecret}"/>
<beans:constructor-arg value="${twitter.oauth.accessToken}"/>
<beans:constructor-arg value="${twitter.oauth.accessTokenSecret}"/>
</beans:bean>
<channel id="search" />
<twitter:search-outbound-gateway request-channel="search" twitter-template="twitterTemplate"
reply-channel="inbound" />
<service-activator input-channel="inbound" ref="twitterAnnouncer" method="searchResult"/>
<beans:bean id="twitterAnnouncer" class="org.springframework.integration.twitter.ignored.TwitterAnnouncer" />
</beans:beans>

View File

@@ -1,53 +0,0 @@
/*
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.ignored;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.social.twitter.api.SearchParameters;
/**
* @author Gary Russell
*
* @since 4.0
*
*/
public class TestSearchOutboundGateway {
@Test
@Ignore
/*
* In order to run this test you need to provide oauth properties in sample.properties on the classpath.
*/
public void testSearch() throws Exception {
ConfigurableApplicationContext ctx =
new ClassPathXmlApplicationContext("TestSearchOutboundGateway-context.xml", this.getClass());
MessageChannel search = ctx.getBean("search", MessageChannel.class);
search.send(new GenericMessage<String>("#springintegration"));
Thread.sleep(10000);
search.send(new GenericMessage<SearchParameters>(new SearchParameters("#springintegration").count(5)));
Thread.sleep(10000);
search.send(new GenericMessage<SearchParameters>(new SearchParameters("#jjjjunk").count(5)));
Thread.sleep(10000);
ctx.close();
}
}

View File

@@ -1,42 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<context:property-placeholder
location="classpath:twitter.sender.properties"
ignore-unresolvable="true"/>
<beans:bean id="twitterTemplate" class="org.springframework.social.twitter.api.impl.TwitterTemplate">
<beans:constructor-arg value="${twitter.oauth.consumerKey}"/>
<beans:constructor-arg value="${twitter.oauth.consumerSecret}"/>
<beans:constructor-arg value="${twitter.oauth.accessToken}"/>
<beans:constructor-arg value="${twitter.oauth.accessTokenSecret}"/>
</beans:bean>
<channel id="inputChannel"/>
<twitter:dm-outbound-channel-adapter twitter-template="twitterTemplate" channel="inputChannel"/>
<chain input-channel="dmOutboundWithinChain">
<twitter:dm-outbound-channel-adapter twitter-template="twitterTemplate"/>
</chain>
</beans:beans>

View File

@@ -1,73 +0,0 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.ignored;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.twitter.core.TwitterHeaders;
import org.springframework.messaging.MessageChannel;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.util.StringUtils;
/**
* @author Josh Long
* @author Oleg Zhurakouksy
* @author Artem Bilan
*/
@ContextConfiguration
public class TestSendingDMsUsingNamespace extends AbstractJUnit4SpringContextTests {
@Autowired
@Qualifier("inputChannel")
private MessageChannel inputChannel;
@Autowired
@Qualifier("dmOutboundWithinChain")
private MessageChannel dmOutboundWithinChain;
@Test
@Ignore
public void testSendigRealDirectMessage() throws Throwable {
String dmUsr = "z_oleg";
MessageBuilder<String> mb = MessageBuilder.withPayload("'Hello world!', from the Spring Integration outbound Twitter adapter "
+ System.currentTimeMillis());
if (StringUtils.hasText(dmUsr)) {
mb.setHeader(TwitterHeaders.DM_TARGET_USER_ID, dmUsr);
}
inputChannel.send(mb.build());
}
@Test
@Ignore
public void testSendigDirectMessageFromChain() throws Throwable {
String dmUsr = "z_oleg";
MessageBuilder<String> mb = MessageBuilder.withPayload("Hello world!");
if (StringUtils.hasText(dmUsr)) {
mb.setHeader(TwitterHeaders.DM_TARGET_USER_ID, dmUsr);
}
dmOutboundWithinChain.send(mb.build());
}
}

View File

@@ -1,42 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/integration"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<context:property-placeholder
location="classpath:twitter.receiver.properties"
ignore-unresolvable="true"/>
<beans:bean id="twitterTemplate" class="org.springframework.social.twitter.api.impl.TwitterTemplate">
<beans:constructor-arg value="${twitter.oauth.consumerKey}"/>
<beans:constructor-arg value="${twitter.oauth.consumerSecret}"/>
<beans:constructor-arg value="${twitter.oauth.accessToken}"/>
<beans:constructor-arg value="${twitter.oauth.accessTokenSecret}"/>
</beans:bean>
<channel id="out"/>
<twitter:outbound-channel-adapter twitter-template="twitterTemplate" channel="out"/>
<chain input-channel="outFromChain">
<twitter:outbound-channel-adapter twitter-template="twitterTemplate"/>
</chain>
</beans:beans>

View File

@@ -1,66 +0,0 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.ignored;
import java.util.Date;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
/**
* @author Josh Long
* @author Artem Bilan
*/
@ContextConfiguration
public class TestSendingUpdatesUsingNamespace extends AbstractJUnit4SpringContextTests {
private MessagingTemplate messagingTemplate = new MessagingTemplate();
@Value("#{out}")
private MessageChannel channel;
@Autowired
@Qualifier("outFromChain")
private MessageChannel outFromChain;
@Test
@Ignore
public void testSendingATweet() throws Throwable {
MessageBuilder<String> mb = MessageBuilder.withPayload("Early start today"
+ new Date(System.currentTimeMillis()));
Message<String> m = mb.build();
this.messagingTemplate.send(this.channel, m);
}
@Test
@Ignore
public void testSendingATweetFromChain() throws Throwable {
Message<String> m = MessageBuilder.withPayload("Early start today" + new Date(System.currentTimeMillis())).build();
this.outFromChain.send(m);
}
}

View File

@@ -1,72 +0,0 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.ignored;
import java.util.Collection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.history.MessageHistory;
import org.springframework.messaging.Message;
import org.springframework.social.twitter.api.DirectMessage;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.stereotype.Component;
/**
* @author Oleg Zhurakousky
* @author Mark Fisher
* @author Gary Russell
*
*/
@Component
public class TwitterAnnouncer {
private final Log logger = LogFactory.getLog(getClass());
public void dm(DirectMessage directMessage) {
logger.info("A direct message has been received from " +
directMessage.getSender().getScreenName() + " with text " + directMessage.getText());
}
public void search(Message<?> search) {
MessageHistory history = MessageHistory.read(search);
Tweet tweet = (Tweet) search.getPayload();
logger.info("A search item was received " +
tweet.getCreatedAt() + " with text " + tweet.getText());
}
public void mention(Tweet s) {
logger.info("A tweet mentioning (or replying) to you was received having text "
+ s.getFromUser() + "-" + s.getText() + " from " + s.getSource());
}
public void searchResult(Collection<Tweet> tweets) {
if (tweets.size() == 0) {
logger.info("No results");
}
for (Tweet s : tweets) {
logger.info("Search result: "
+ s.getFromUser() + "-" + s.getText() + " from " + s.getSource());
}
}
public void updates(Tweet t) {
logger.info("Received timeline update: " + t.getText() + " from " + t.getSource());
}
}

View File

@@ -1,63 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.messaging.Message;
import org.springframework.social.twitter.api.DirectMessage;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
*/
public class DirectMessageReceivingMessageSourceTests {
private final Log logger = LogFactory.getLog(getClass());
@SuppressWarnings("unchecked")
@Test
@Ignore
public void demoReceiveDm() throws Exception {
PropertiesFactoryBean pf = new PropertiesFactoryBean();
pf.setLocation(new ClassPathResource("sample.properties"));
pf.afterPropertiesSet();
Properties prop = pf.getObject();
TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"),
prop.getProperty("z_oleg.oauth.consumerSecret"),
prop.getProperty("z_oleg.oauth.accessToken"),
prop.getProperty("z_oleg.oauth.accessTokenSecret"));
DirectMessageReceivingMessageSource tSource = new DirectMessageReceivingMessageSource(template, "foo");
tSource.afterPropertiesSet();
for (int i = 0; i < 50; i++) {
Message<DirectMessage> message = (Message<DirectMessage>) tSource.receive();
if (message != null) {
DirectMessage tweet = message.getPayload();
logger.info(tweet.getSender().getScreenName() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
}
}
}
}

View File

@@ -1,181 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.integration.metadata.SimpleMetadataStore;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.social.twitter.api.SearchMetadata;
import org.springframework.social.twitter.api.SearchOperations;
import org.springframework.social.twitter.api.SearchParameters;
import org.springframework.social.twitter.api.SearchResults;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
/**
* @author Oleg Zhurakousky
* @author Gunnar Hillert
* @author Gary Russell
*/
public class SearchReceivingMessageSourceTests {
private final Log logger = LogFactory.getLog(getClass());
private static final String SEARCH_QUERY = "#springsource";
@SuppressWarnings("unchecked")
@Test
@Ignore
public void demoReceiveSearchResults() throws Exception {
PropertiesFactoryBean pf = new PropertiesFactoryBean();
pf.setLocation(new ClassPathResource("sample.properties"));
pf.afterPropertiesSet();
Properties prop = pf.getObject();
TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"),
prop.getProperty("z_oleg.oauth.consumerSecret"),
prop.getProperty("z_oleg.oauth.accessToken"),
prop.getProperty("z_oleg.oauth.accessTokenSecret"));
SearchReceivingMessageSource tSource = new SearchReceivingMessageSource(template, "foo");
tSource.setQuery(SEARCH_QUERY);
tSource.afterPropertiesSet();
for (int i = 0; i < 50; i++) {
Message<Tweet> message = (Message<Tweet>) tSource.receive();
if (message != null) {
Tweet tweet = message.getPayload();
logger.info(tweet.getFromUser() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
}
}
}
/**
* Unit Test ensuring some basic initialization properties being set.
*/
@Test
public void testSearchReceivingMessageSourceInit() {
final SearchReceivingMessageSource messageSource =
new SearchReceivingMessageSource(new TwitterTemplate("test"), "foo");
messageSource.setComponentName("twitterSearchMessageSource");
final Object metadataStore = TestUtils.getPropertyValue(messageSource, "metadataStore");
final Object metadataKey = TestUtils.getPropertyValue(messageSource, "metadataKey");
assertNull(metadataStore);
assertNotNull(metadataKey);
messageSource.setBeanFactory(mock(BeanFactory.class));
messageSource.afterPropertiesSet();
final Object metadataStoreInitialized = TestUtils.getPropertyValue(messageSource, "metadataStore");
final Object metadataKeyInitialized = TestUtils.getPropertyValue(messageSource, "metadataKey");
assertNotNull(metadataStoreInitialized);
assertTrue(metadataStoreInitialized instanceof SimpleMetadataStore);
assertNotNull(metadataKeyInitialized);
assertEquals("foo", metadataKeyInitialized);
final Twitter twitter = TestUtils.getPropertyValue(messageSource, "twitter", Twitter.class);
assertFalse(twitter.isAuthorized());
assertNotNull(twitter.userOperations());
}
/**
* This test ensures that when polling for a list of Tweets null is never returned.
* In case of no polling results, an empty list is returned instead.
*/
@Test
public void testPollForTweetsNullResults() {
final TwitterTemplate twitterTemplate = mock(TwitterTemplate.class);
final SearchOperations so = mock(SearchOperations.class);
when(twitterTemplate.searchOperations()).thenReturn(so);
when(twitterTemplate.searchOperations().search(SEARCH_QUERY, 20, 0, 0)).thenReturn(null);
final SearchReceivingMessageSource messageSource = new SearchReceivingMessageSource(twitterTemplate, "foo");
messageSource.setQuery(SEARCH_QUERY);
final String setQuery = TestUtils.getPropertyValue(messageSource, "query", String.class);
assertEquals(SEARCH_QUERY, setQuery);
assertEquals("twitter:search-inbound-channel-adapter", messageSource.getComponentType());
final List<Tweet> tweets = messageSource.pollForTweets(0);
assertNotNull(tweets);
assertTrue(tweets.isEmpty());
}
/**
* Verify that a polling operation returns in fact 3 results.
*/
@Test
public void testPollForTweetsThreeResults() {
final TwitterTemplate twitterTemplate;
final SearchOperations so = mock(SearchOperations.class);
final List<Tweet> tweets = new ArrayList<Tweet>();
tweets.add(mock(Tweet.class));
tweets.add(mock(Tweet.class));
tweets.add(mock(Tweet.class));
final SearchResults results = new SearchResults(tweets, new SearchMetadata(111, 111));
twitterTemplate = mock(TwitterTemplate.class);
when(twitterTemplate.searchOperations()).thenReturn(so);
SearchParameters params = new SearchParameters(SEARCH_QUERY).count(20).sinceId(0);
when(twitterTemplate.searchOperations().search(params)).thenReturn(results);
final SearchReceivingMessageSource messageSource = new SearchReceivingMessageSource(twitterTemplate, "foo");
messageSource.setQuery(SEARCH_QUERY);
final List<Tweet> tweetSearchResults = messageSource.pollForTweets(0);
assertNotNull(tweetSearchResults);
assertEquals(3, tweetSearchResults.size());
}
}

View File

@@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-twitter="http://www.springframework.org/schema/integration/twitter"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="org.springframework.integration.twitter.inbound.SearchReceivingMessageSourceWithRedisTests$SearchReceivingMessageSourceWithRedisTestsConfig"/>
<int:channel id="inbound_twitter">
<int:queue/>
</int:channel>
<int-twitter:search-inbound-channel-adapter id="twitterSearchAdapter"
query="springintegration"
twitter-template="twitterTemplate"
channel="inbound_twitter"
metadata-store="redisMetadataStore"
auto-startup="false">
<int:poller fixed-delay="100" max-messages-per-poll="3"/>
</int-twitter:search-inbound-channel-adapter>
<bean id="redisMetadataStore" class="org.springframework.integration.redis.metadata.RedisMetadataStore">
<constructor-arg name="connectionFactory"
value="#{T (org.springframework.integration.redis.rules.RedisAvailableRule).connectionFactory}"/>
</bean>
</beans>

View File

@@ -1,200 +0,0 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.endpoint.SourcePollingChannelAdapter;
import org.springframework.integration.metadata.MetadataStore;
import org.springframework.integration.redis.metadata.RedisMetadataStore;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.test.rule.Log4j2LevelAdjuster;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.PollableChannel;
import org.springframework.social.twitter.api.SearchMetadata;
import org.springframework.social.twitter.api.SearchOperations;
import org.springframework.social.twitter.api.SearchParameters;
import org.springframework.social.twitter.api.SearchResults;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.UserOperations;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Gunnar Hillert
* @author Artem Bilan
* @author Gary Russell
*
* @since 3.0
*/
@ContextConfiguration("SearchReceivingMessageSourceWithRedisTests-context.xml")
@RunWith(SpringRunner.class)
@DirtiesContext
public class SearchReceivingMessageSourceWithRedisTests extends RedisAvailableTests {
@Rule
public Log4j2LevelAdjuster adjuster = Log4j2LevelAdjuster.trace();
@Autowired
private SourcePollingChannelAdapter twitterSearchAdapter;
@Autowired
private AbstractTwitterMessageSource<?> twitterMessageSource;
@Autowired
private MetadataStore metadataStore;
@Autowired
@Qualifier("inbound_twitter")
private PollableChannel tweets;
@Test
@RedisAvailable
public void testPollForTweetsThreeResultsWithRedisMetadataStore() throws Exception {
String metadataKey = TestUtils.getPropertyValue(twitterSearchAdapter, "source.metadataKey", String.class);
// There is need to set a value, not 'remove' and re-init 'twitterMessageSource'
this.metadataStore.put(metadataKey, "-1");
this.twitterMessageSource.afterPropertiesSet();
MetadataStore metadataStore = TestUtils.getPropertyValue(this.twitterSearchAdapter, "source.metadataStore",
MetadataStore.class);
assertTrue("Expected metadataStore to be an instance of RedisMetadataStore",
metadataStore instanceof RedisMetadataStore);
assertSame(this.metadataStore, metadataStore);
assertEquals("twitterSearchAdapter.74", metadataKey);
this.twitterSearchAdapter.start();
Message<?> receive = this.tweets.receive(10000);
assertNotNull(receive);
receive = this.tweets.receive(10000);
assertNotNull(receive);
receive = this.tweets.receive(10000);
assertNotNull(receive);
/* We received 3 messages so far. When invoking receive() again the search
* will return again the 3 test Tweets but as we already processed them
* no message (null) is returned. */
assertNull(this.tweets.receive(0));
String persistedMetadataStoreValue = this.metadataStore.get(metadataKey);
assertNotNull(persistedMetadataStoreValue);
assertEquals("3", persistedMetadataStoreValue);
this.twitterSearchAdapter.stop();
this.metadataStore.put(metadataKey, "1");
this.twitterMessageSource.afterPropertiesSet();
this.twitterSearchAdapter.start();
receive = this.tweets.receive(10000);
assertNotNull(receive);
assertThat(receive.getPayload(), instanceOf(Tweet.class));
assertEquals(((Tweet) receive.getPayload()).getId(), 2L);
receive = this.tweets.receive(10000);
assertNotNull(receive);
assertThat(receive.getPayload(), instanceOf(Tweet.class));
assertEquals(((Tweet) receive.getPayload()).getId(), 3L);
assertNull(this.tweets.receive(0));
persistedMetadataStoreValue = this.metadataStore.get(metadataKey);
assertNotNull(persistedMetadataStoreValue);
assertEquals("3", persistedMetadataStoreValue);
}
@Configuration
public static class SearchReceivingMessageSourceWithRedisTestsConfig {
@Bean(name = "twitterTemplate")
public TwitterTemplate twitterTemplate() {
TwitterTemplate twitterTemplate = mock(TwitterTemplate.class);
SearchOperations so = mock(SearchOperations.class);
Tweet tweet3 = mock(Tweet.class);
given(tweet3.getId()).willReturn(3L);
given(tweet3.getCreatedAt()).willReturn(new GregorianCalendar(2013, 2, 20).getTime());
given(tweet3.toString()).will(invocation -> "Mock for Tweet: " + tweet3.getId());
Tweet tweet1 = mock(Tweet.class);
given(tweet1.getId()).willReturn(1L);
given(tweet1.getCreatedAt()).willReturn(new GregorianCalendar(2013, 0, 20).getTime());
given(tweet1.toString()).will(invocation -> "Mock for Tweet: " + tweet1.getId());
final Tweet tweet2 = mock(Tweet.class);
given(tweet2.getId()).willReturn(2L);
given(tweet2.getCreatedAt()).willReturn(new GregorianCalendar(2013, 1, 20).getTime());
given(tweet2.toString()).will(invocation -> "Mock for Tweet: " + tweet2.getId());
final List<Tweet> tweets = new ArrayList<Tweet>();
tweets.add(tweet3);
tweets.add(tweet1);
tweets.add(tweet2);
final SearchResults results = new SearchResults(tweets, new SearchMetadata(111, 111));
when(twitterTemplate.searchOperations()).thenReturn(so);
when(twitterTemplate.searchOperations().search(any(SearchParameters.class))).thenReturn(results);
when(twitterTemplate.isAuthorized()).thenReturn(true);
final UserOperations userOperations = mock(UserOperations.class);
when(twitterTemplate.userOperations()).thenReturn(userOperations);
when(userOperations.getProfileId()).thenReturn(74L);
return twitterTemplate;
}
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.inbound;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.messaging.Message;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
*/
public class TimelineReceivingMessageSourceTests {
private final Log logger = LogFactory.getLog(getClass());
@SuppressWarnings("unchecked")
@Test
@Ignore
public void demoReceiveTimeline() throws Exception {
PropertiesFactoryBean pf = new PropertiesFactoryBean();
pf.setLocation(new ClassPathResource("sample.properties"));
pf.afterPropertiesSet();
Properties prop = pf.getObject();
TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"),
prop.getProperty("z_oleg.oauth.consumerSecret"),
prop.getProperty("z_oleg.oauth.accessToken"),
prop.getProperty("z_oleg.oauth.accessTokenSecret"));
TimelineReceivingMessageSource tSource = new TimelineReceivingMessageSource(template, "foo");
tSource.afterPropertiesSet();
for (int i = 0; i < 50; i++) {
Message<Tweet> message = (Message<Tweet>) tSource.receive();
if (message != null) {
Tweet tweet = message.getPayload();
logger.info(tweet.getFromUser() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
}
}
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.outbound;
import java.util.Properties;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.twitter.core.TwitterHeaders;
import org.springframework.messaging.Message;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
/**
* @author Oleg Zhurakousky
* @author Mark Fisher
* @author Gary Russell
*/
public class DirectMessageSendingMessageHandlerTests {
@Test
@Ignore
public void validateSendDirectMessage() throws Exception {
PropertiesFactoryBean pf = new PropertiesFactoryBean();
pf.setLocation(new ClassPathResource("sample.properties"));
pf.afterPropertiesSet();
Properties prop = pf.getObject();
TwitterTemplate template = new TwitterTemplate(prop.getProperty("spring_eip.oauth.consumerKey"),
prop.getProperty("spring_eip.oauth.consumerSecret"),
prop.getProperty("spring_eip.oauth.accessToken"),
prop.getProperty("spring_eip.oauth.accessTokenSecret"));
Message<?> message1 = MessageBuilder.withPayload("Polsihing SI Twitter migration")
.setHeader(TwitterHeaders.DM_TARGET_USER_ID, "z_oleg").build();
DirectMessageSendingMessageHandler handler = new DirectMessageSendingMessageHandler(template);
handler.afterPropertiesSet();
handler.handleMessage(message1);
}
}

View File

@@ -1,21 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd">
<bean id="tt" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="org.springframework.social.twitter.api.Twitter" />
</bean>
<int-twitter:outbound-channel-adapter id="in1" twitter-template="tt" />
<int-twitter:outbound-channel-adapter
id="in2"
twitter-template="tt"
tweet-data-expression="new TweetData(payload.foo).withMedia(headers.media)"/>
</beans>

View File

@@ -1,111 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.outbound;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.Collections;
import java.util.Properties;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.social.twitter.api.TimelineOperations;
import org.springframework.social.twitter.api.TweetData;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.MultiValueMap;
/**
* @author Oleg Zhurakousky
* @author Artem Bilan
* @since 2.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class StatusUpdatingMessageHandlerTests {
@Autowired
MessageChannel in1;
@Autowired
MessageChannel in2;
@Autowired
Twitter twitter;
@Test
@Ignore
public void demoSendStatusMessage() throws Exception {
PropertiesFactoryBean pf = new PropertiesFactoryBean();
pf.setLocation(new ClassPathResource("sample.properties"));
pf.afterPropertiesSet();
Properties prop = pf.getObject();
TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"),
prop.getProperty("z_oleg.oauth.consumerSecret"),
prop.getProperty("z_oleg.oauth.accessToken"),
prop.getProperty("z_oleg.oauth.accessTokenSecret"));
Message<?> message1 = new GenericMessage<>("Polishing #springintegration migration to Spring Social. test");
StatusUpdatingMessageHandler handler = new StatusUpdatingMessageHandler(template);
handler.afterPropertiesSet();
handler.handleMessage(message1);
}
@Test
public void testStatusUpdatingMessageHandler() {
TimelineOperations timelineOperations = Mockito.mock(TimelineOperations.class);
Mockito.when(this.twitter.timelineOperations()).thenReturn(timelineOperations);
ArgumentCaptor<TweetData> argument = ArgumentCaptor.forClass(TweetData.class);
this.in1.send(new GenericMessage<String>("foo"));
Mockito.verify(timelineOperations).updateStatus(argument.capture());
assertEquals("foo", argument.getValue().toRequestParameters().getFirst("status"));
Mockito.reset(timelineOperations);
ClassPathResource media = new ClassPathResource("log4j.properties");
this.in2.send(MessageBuilder.withPayload(Collections.singletonMap("foo", "bar"))
.setHeader("media", media)
.build());
Mockito.verify(timelineOperations).updateStatus(argument.capture());
TweetData tweetData = argument.getValue();
MultiValueMap<String, Object> requestParameters = tweetData.toRequestParameters();
assertEquals("bar", requestParameters.getFirst("status"));
assertNull(requestParameters.getFirst("media"));
MultiValueMap<String, Object> uploadMediaParameters = tweetData.toUploadMediaParameters();
assertEquals(media, uploadMediaParameters.getFirst("media"));
}
}

View File

@@ -1,240 +0,0 @@
/*
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.twitter.outbound;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.twitter.core.TwitterHeaders;
import org.springframework.integration.twitter.outbound.TwitterSearchOutboundGatewayTests.TwitterConfig;
import org.springframework.messaging.Message;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.social.twitter.api.SearchMetadata;
import org.springframework.social.twitter.api.SearchOperations;
import org.springframework.social.twitter.api.SearchParameters;
import org.springframework.social.twitter.api.SearchResults;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Gary Russell
* @author Artem Bilan
* @since 4.0
*
*/
@ContextConfiguration(classes = TwitterConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class TwitterSearchOutboundGatewayTests {
@Autowired
private SearchOperations searchOps;
@Autowired
private TwitterSearchOutboundGateway gateway;
@Autowired
private PollableChannel outputChannel;
@Test
public void testStringQuery() {
Tweet tweet = mock(Tweet.class);
SearchMetadata searchMetadata = mock(SearchMetadata.class);
final SearchResults searchResults = new SearchResults(Collections.singletonList(tweet), searchMetadata);
doAnswer(invocation -> {
SearchParameters searchParameters = invocation.getArgument(0);
assertEquals("foo", searchParameters.getQuery());
assertEquals(Integer.valueOf(20), searchParameters.getCount());
return searchResults;
}).when(this.searchOps).search(any(SearchParameters.class));
this.gateway.handleMessage(new GenericMessage<String>("foo"));
Message<?> reply = this.outputChannel.receive(0);
assertNotNull(reply);
@SuppressWarnings("unchecked")
List<Tweet> tweets = (List<Tweet>) reply.getPayload();
assertEquals(1, tweets.size());
assertSame(tweet, tweets.get(0));
assertSame(searchMetadata, reply.getHeaders().get(TwitterHeaders.SEARCH_METADATA));
}
@Test
public void testStringQueryCustomLimit() {
this.gateway.setSearchArgsExpression(new SpelExpressionParser()
.parseExpression("{payload, 30}"));
Tweet tweet = mock(Tweet.class);
SearchMetadata searchMetadata = mock(SearchMetadata.class);
final SearchResults searchResults = new SearchResults(Collections.singletonList(tweet), searchMetadata);
doAnswer(invocation -> {
SearchParameters searchParameters = invocation.getArgument(0);
assertEquals("foo", searchParameters.getQuery());
assertEquals(Integer.valueOf(30), searchParameters.getCount());
return searchResults;
}).when(this.searchOps).search(any(SearchParameters.class));
this.gateway.handleMessage(new GenericMessage<String>("foo"));
Message<?> reply = this.outputChannel.receive(0);
assertNotNull(reply);
@SuppressWarnings("unchecked")
List<Tweet> tweets = (List<Tweet>) reply.getPayload();
assertEquals(1, tweets.size());
assertSame(tweet, tweets.get(0));
assertSame(searchMetadata, reply.getHeaders().get(TwitterHeaders.SEARCH_METADATA));
}
@Test
public void testStringQueryCustomExpression() {
this.gateway.setSearchArgsExpression(new SpelExpressionParser()
.parseExpression("{'bar', 1, 2, 3}"));
Tweet tweet = mock(Tweet.class);
SearchMetadata searchMetadata = mock(SearchMetadata.class);
final SearchResults searchResults = new SearchResults(Collections.singletonList(tweet), searchMetadata);
doAnswer(invocation -> {
SearchParameters searchParameters = invocation.getArgument(0);
assertEquals("bar", searchParameters.getQuery());
assertEquals(Integer.valueOf(1), searchParameters.getCount());
assertEquals(Long.valueOf(2), searchParameters.getSinceId());
assertEquals(Long.valueOf(3), searchParameters.getMaxId());
return searchResults;
}).when(this.searchOps).search(any(SearchParameters.class));
this.gateway.handleMessage(new GenericMessage<String>("foo"));
Message<?> reply = this.outputChannel.receive(0);
assertNotNull(reply);
@SuppressWarnings("unchecked")
List<Tweet> tweets = (List<Tweet>) reply.getPayload();
assertEquals(1, tweets.size());
assertSame(tweet, tweets.get(0));
assertSame(searchMetadata, reply.getHeaders().get(TwitterHeaders.SEARCH_METADATA));
}
@Test
public void testSearchParamsQuery() {
Tweet tweet = mock(Tweet.class);
SearchMetadata searchMetadata = mock(SearchMetadata.class);
final SearchResults searchResults = new SearchResults(Collections.singletonList(tweet), searchMetadata);
final SearchParameters parameters = new SearchParameters("bar");
doAnswer(invocation -> {
SearchParameters searchParameters = invocation.getArgument(0);
assertSame(parameters, searchParameters);
return searchResults;
}).when(this.searchOps).search(any(SearchParameters.class));
this.gateway.handleMessage(new GenericMessage<SearchParameters>(parameters));
Message<?> reply = this.outputChannel.receive(0);
assertNotNull(reply);
@SuppressWarnings("unchecked")
List<Tweet> tweets = (List<Tweet>) reply.getPayload();
assertEquals(1, tweets.size());
assertSame(tweet, tweets.get(0));
assertSame(searchMetadata, reply.getHeaders().get(TwitterHeaders.SEARCH_METADATA));
}
@Test
public void testSearchParamsQueryCustomExpression() {
this.gateway.setSearchArgsExpression(new SpelExpressionParser()
.parseExpression("new SearchParameters('foo' + payload).count(5).sinceId(11)"));
Tweet tweet = mock(Tweet.class);
SearchMetadata searchMetadata = mock(SearchMetadata.class);
final SearchResults searchResults = new SearchResults(Collections.singletonList(tweet), searchMetadata);
doAnswer(invocation -> {
SearchParameters searchParameters = invocation.getArgument(0);
assertEquals("foobar", searchParameters.getQuery());
assertEquals(Integer.valueOf(5), searchParameters.getCount());
assertEquals(Long.valueOf(11), searchParameters.getSinceId());
return searchResults;
}).when(this.searchOps).search(any(SearchParameters.class));
this.gateway.handleMessage(new GenericMessage<String>("bar"));
Message<?> reply = this.outputChannel.receive(0);
assertNotNull(reply);
@SuppressWarnings("unchecked")
List<Tweet> tweets = (List<Tweet>) reply.getPayload();
assertEquals(1, tweets.size());
assertSame(tweet, tweets.get(0));
assertSame(searchMetadata, reply.getHeaders().get(TwitterHeaders.SEARCH_METADATA));
}
@Test
public void testEmptyResult() {
SearchMetadata searchMetadata = mock(SearchMetadata.class);
List<Tweet> empty = new ArrayList<Tweet>(0);
final SearchResults searchResults = new SearchResults(empty, searchMetadata);
doAnswer(invocation -> {
SearchParameters searchParameters = invocation.getArgument(0);
assertEquals("foo", searchParameters.getQuery());
assertEquals(Integer.valueOf(20), searchParameters.getCount());
return searchResults;
}).when(this.searchOps).search(any(SearchParameters.class));
this.gateway.handleMessage(new GenericMessage<String>("foo"));
Message<?> reply = this.outputChannel.receive(0);
assertNotNull(reply);
@SuppressWarnings("unchecked")
List<Tweet> tweets = (List<Tweet>) reply.getPayload();
assertEquals(0, tweets.size());
assertSame(searchMetadata, reply.getHeaders().get(TwitterHeaders.SEARCH_METADATA));
}
@Configuration
@EnableIntegration
public static class TwitterConfig {
@Bean
public TwitterSearchOutboundGateway gateway() {
TwitterSearchOutboundGateway gateway = new TwitterSearchOutboundGateway(twitter());
gateway.setOutputChannel(outputChannel());
return gateway;
}
@Bean
public PollableChannel outputChannel() {
return new QueueChannel();
}
@Bean
public Twitter twitter() {
Twitter twitter = mock(Twitter.class);
when(twitter.searchOperations()).thenReturn(searchOps());
return twitter;
}
@Bean
public SearchOperations searchOps() {
return mock(SearchOperations.class);
}
}
}

View File

@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %p [%t] [%c] - %m%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="org.springframework.integration" level="warn"/>
<Logger name="org.springframework.integration.twitter" level="warn"/>
<Root level="warn">
<AppenderRef ref="STDOUT" />
</Root>
</Loggers>
</Configuration>

View File

@@ -1,5 +0,0 @@
# oauth setup for prosibook twitter account
twitter.oauth.consumerKey=
twitter.oauth.consumerSecret=
twitter.oauth.accessToken=
twitter.oauth.accessTokenSecret=

View File

@@ -1,5 +0,0 @@
twitter.oauth.consumerKey=
twitter.oauth.consumerSecret=
twitter.oauth.accessToken=
twitter.oauth.accessTokenSecret=
twitter.oauth.pin=

View File

@@ -88,9 +88,9 @@ See also the following blog: http://blog.springsource.com/2010/03/29/using-udp-a
[[new-twitter]]
===== Twitter Adapters
Twitter adapters provide support for sending and receiving Twitter status updates and direct messages.
You can also perform Twitter searches with an inbound channel adapter.
See "`<<twitter>>`" for more details.
Twitter adapters provides support for sending and receiving Twitter Status updates as well as Direct Messages.
You can also perform Twitter Searches with an inbound Channel Adapter.
See https://github.com/spring-projects/spring-integration-extensions/tree/master/spring-integration-social-twitter[Spring Integration Social Twitter] for more details.
[[new-xmpp]]
===== XMPP Adapters

View File

@@ -126,9 +126,9 @@ For more information, see "`<<annotations>>`".
[[x4.0-twitter-sog]]
===== Twitter Search Outbound Gateway
We added a new twitter endpoint: `<int-twitter-search-outbound-gateway/>`.
Unlike the search inbound adapter, which polls by using the same search query each time, the outbound gateway allows on-demand customized queries.
For more information, see "`<<twitter-sog>>`".
A new twitter endpoint `<int-twitter-search-outbound-gateway/>` has been added.
Unlike the search inbound adapter which polls using the same search query each time, the outbound gateway allows on-demand customized queries.
For more information, see https://github.com/spring-projects/spring-integration-extensions/tree/master/spring-integration-social-twitter[Spring Integration Social Twitter].
[[x4.0-gemfire-metadata]]
===== Gemfire Metadata Store
@@ -246,9 +246,8 @@ See "`<<ftp-session-factory>>`" for more information.
[[x4.0-twitter-status-updating]]
===== Twitter: `StatusUpdatingMessageHandler`
The `StatusUpdatingMessageHandler` (`<int-twitter:outbound-channel-adapter>`) now supports the `tweet-data-expression` attribute to build a `org.springframework.social.twitter.api.TweetData` object for updating the timeline status.
This feature allows, for example, attaching an image.
See "`<<outbound-twitter-update>>`" for more information.
The `StatusUpdatingMessageHandler` (`<int-twitter:outbound-channel-adapter>`) now supports the `tweet-data-expression` attribute to build a `org.springframework.social.twitter.api.TweetData` object for updating the timeline status allowing, for example, attaching an image.
See https://github.com/spring-projects/spring-integration-extensions/tree/master/spring-integration-social-twitter[Spring Integration Social Twitter] for more information.
[[x4.0-jpa-id-expression]]
===== JPA Retrieving Gateway: `id-expression`

View File

@@ -154,12 +154,6 @@ The following table summarizes the various endpoints with quick links to the app
| <<tcp-gateways>>
| <<tcp-gateways>>
| *Twitter*
| <<twitter-inbound>>
| <<twitter-outbound>>
| N
| <<twitter-sog>>
| *UDP*
| <<udp-adapters>>
| <<udp-adapters>>

View File

@@ -246,14 +246,13 @@ Version 4.0 introduced a new Gemfire-based `MetadataStore` (<<metadata-store>>)
You can use the `GemfireMetadataStore` to maintain metadata state across application restarts.
This new `MetadataStore` implementation can be used with adapters such as:
* <<twitter-inbound>>
* <<feed-inbound-channel-adapter>>
* <<file-reading>>
* <<ftp-inbound>>
* <<sftp-inbound>>
To get these adapters to use the new `GemfireMetadataStore`, declare a Spring bean with a bean name of `metadataStore`.
The Twitter inbound channel adapter and the feed inbound channel adapter both automatically pick up and use the declared `GemfireMetadataStore`.
The feed inbound channel adapter automatically picks up and use the declared `GemfireMetadataStore`.
NOTE: The `GemfireMetadataStore` also implements `ConcurrentMetadataStore`, letting it be reliably shared across multiple application instances, where only one instance can store or modify a key's value.
These methods give various levels of concurrency guarantees based on the scope and data policy of the region.

View File

@@ -113,8 +113,6 @@ include::./syslog.adoc[]
include::./ip.adoc[]
include::./twitter.adoc[]
include::./webflux.adoc[]
include::./web-sockets.adoc[]

View File

@@ -1057,13 +1057,14 @@ Version 5.0 introduced the JDBC `MetadataStore` (see "`<<metadata-store>>`") imp
You can use the `JdbcMetadataStore` to maintain the metadata state across application restarts.
This `MetadataStore` implementation can be used with adapters such as the following:
* <<twitter-inbound,Twitter inbound adapters>>
* <<feed-inbound-channel-adapter,Feed inbound channel adapters>>
* <<file-reading,files>>
* <<ftp-inbound,FTP inbound channel adapters>>
* <<sftp-inbound,SFTP inbound channel adapters>>
To configure these adapters to use the `JdbcMetadataStore`, declare a Spring bean by using a bean name of `metadataStore`. The Twitter inbound channel adapter and the feed inbound channel adapter both automatically pick up and use the declared `JdbcMetadataStore`, as the following example shows:
To configure these adapters to use the `JdbcMetadataStore`, declare a Spring bean by using a bean name of `metadataStore`.
The Feed inbound channel adapter and the feed inbound channel adapter both automatically pick up and use the declared `JdbcMetadataStore`, as the following example shows:
====
[source,java]

View File

@@ -160,14 +160,14 @@ Spring Integration 4.2 introduced a new MongoDB-based `MetadataStore` (see "`<<m
You can use the `MongoDbMetadataStore` to maintain metadata state across application restarts.
You can use this new `MetadataStore` implementation with adapters such as:
* <<twitter-inbound,Twitter>>
* <<feed-inbound-channel-adapter,Feed>>
* <<file-reading,File>>
* <<ftp-inbound,FTP>>
* <<sftp-inbound,SFTP>>
To instruct these adapters to use the new `MongoDbMetadataStore`, declare a Spring bean with a bean name of `metadataStore`.
The Twitter inbound channel adapter and the feed inbound channel adapter both automatically pick up and use the declared `MongoDbMetadataStore`.
The feed inbound channel adapter automatically picks up and use the declared `MongoDbMetadataStore`.
The following example shows how to declare a bean with a name of `metadataStore`:
====

View File

@@ -31,8 +31,8 @@ Spring Framework 2.0 introduced support for namespaces, which simplifies the XML
In this reference guide, the `int` namespace prefix is used for Spring Integration's core namespace support.
Each Spring Integration adapter type (also called a module) provides its own namespace, which is configured by using the following convention:
`int-` followed by the name of the module -- for example, `int-twitter`, `int-stream`, and so on.
The following example shows the `int`, `int-twitter`, and `int-stream` namespaces in use:
The following example shows the `int`, `int-event`, and `int-stream` namespaces in use:
====
[source,xml]
@@ -41,15 +41,15 @@ The following example shows the `int`, `int-twitter`, and `int-stream` namespace
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-twitter="http://www.springframework.org/schema/integration/twitter"
xmlns:int-webflux="http://www.springframework.org/schema/integration/webflux"
xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/twitter
http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd
http://www.springframework.org/schema/integration/webflux
http://www.springframework.org/schema/integration/webflux/spring-integration-webflux.xsd
http://www.springframework.org/schema/integration/stream
http://www.springframework.org/schema/integration/stream/spring-integration-stream.xsd">

View File

@@ -397,14 +397,14 @@ Spring Integration 3.0 introduced a new Redis-based http://docs.spring.io/spring
You can use the `RedisMetadataStore` to maintain the state of a `MetadataStore` across application restarts.
You can use this new `MetadataStore` implementation with adapters such as:
* <<twitter-inbound,Twitter>>
* <<feed-inbound-channel-adapter,Feed>>
* <<file-reading,File>>
* <<ftp-inbound,FTP>>
* <<sftp-inbound,SFTP>>
To instruct these adapters to use the new `RedisMetadataStore`, declare a Spring bean named `metadataStore`.
The Twitter inbound channel adapter and the feed inbound channel adapter both automatically pick up and use the declared `RedisMetadataStore`.
The Feed inbound channel adapter and the feed inbound channel adapter both automatically pick up and use the declared `RedisMetadataStore`.
The following example shows how to declare such a bean:
====

View File

@@ -1,387 +0,0 @@
[[twitter]]
== Twitter Support
Spring Integration provides support for interacting with Twitter.
With the Twitter adapters, you can both receive and send Twitter messages.
You can also perform a Twitter search based on a schedule and publish the search results within messages.
Since version 4.0, a search outbound gateway is provided to perform dynamic searches.
Twitter is a social networking and micro-blogging service that enables its users to send and read messages known as tweets.
Tweets are text-based posts of up to 280 characters (up from 140 in 2018) displayed on the author's profile page and delivered to the author's subscribers, who are known as followers.
IMPORTANT: Versions of Spring Integration prior to 2.1 were dependent upon the http://twitter4j.org[Twitter4J API].
However, with the release of http://projects.spring.io/spring-social[Spring Social 1.0 GA], Spring Integration (as of version 2.1) now builds directly upon Spring Social's Twitter support, instead of Twitter4J.
All Twitter endpoints require the configuration of a `TwitterTemplate`, because even search operations require an authenticated template.
Spring Integration provides a convenient namespace configuration to define Twitter artifacts.
You can enable it by adding the following within your XML header:
====
[source,xml]
----
xmlns:int-twitter="http://www.springframework.org/schema/integration/twitter"
xsi:schemaLocation="http://www.springframework.org/schema/integration/twitter
http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd"
----
====
[[twitter-oauth]]
=== Twitter OAuth Configuration
For authenticated operations, Twitter uses OAuth, an authentication protocol that lets users approve an application to act on their behalf without sharing their password.
More information can be found at http://oauth.net[http://oauth.net] or in http://hueniverse.com/oauth[this article] from Hueniverse.
See the http://dev.twitter.com/pages/oauth_faq[OAuth FAQ] for more information about OAuth and Twitter.
In order to use OAuth authentication and authorization with Twitter, you must create a new application on the Twitter Developers site.
The following directions describe how to create a new application and obtain consumer keys and an access token:
. Go to http://dev.twitter.com[http://dev.twitter.com].
. Click on the `Register an app` link and fill out all required fields on the form provided.
Set `Application Type` to `Client` and, depending on the nature of your application, set `Default Access Type` to `Read & Write` or `Read-only`.
Submit the form.
If everything is successful, you see the `Consumer Key` and `Consumer Secret`.
Copy both values in a safe place.
. On the same page, you should see a `My Access Token` button on the side bar (right).
Click on it and you should see two more values: `Access Token` and `Access Token Secret`.
Copy these values in a safe place as well.
=== Twitter Template
As <<twitter,mentioned earlier>>, Spring Integration relies upon Spring Social.
That library provides an implementation of the template pattern( `o.s.social.twitter.api.impl.TwitterTemplate`) to let you interact with Twitter.
For anonymous operations (such as search), you need not explicitly define an instance of `TwitterTemplate`, since a default instance is created and injected into the endpoint.
However, for authenticated operations (update status, send direct message, asd others), you must configure a `TwitterTemplate` as a bean and inject it explicitly into the endpoint, because the authentication configuration is required.
The following example configures a TwitterTemplate:
====
[source,xml]
----
<bean id="twitterTemplate" class="o.s.social.twitter.api.impl.TwitterTemplate">
<constructor-arg value="4XzBPacJQxyBzzzH"/>
<constructor-arg value="AbRxUAvyCtqQtvxFK8w5ZMtMj20KFhB6o"/>
<constructor-arg value="21691649-4YZY5iJEOfz2A9qCFd9SjBRGb3HLmIm4HNE"/>
<constructor-arg value="AbRxUAvyNCtqQtxFK8w5ZMtMj20KFhB6o"/>
</bean>
----
====
NOTE: The values above are not real.
As the preceding configuration shows, all you need to do is to provide OAuth `attributes` as constructor arguments.
The values should be those you obtained in the previous step.
The order of constructor arguments is:
. `consumerKey`
. `consumerSecret`
. `accessToken`
. `accessTokenSecret`.
A more practical way to manage OAuth connection attributes is to use Spring's property placeholder support by creating a property file (for example, oauth.properties), as the following example shows:
====
[source,java]
----
twitter.oauth.consumerKey=4XzBPacJQxyBzzzH
twitter.oauth.consumerSecret=AbRxUAvyCtqQtvxFK8w5ZMtMj20KFhB6o
twitter.oauth.accessToken=21691649-4YZY5iJEOfz2A9qCFd9SjBRGb3HLmIm4HNE
twitter.oauth.accessTokenSecret=AbRxUAvyNCtqQtxFK8w5ZMtMj20KFhB6o
----
====
Then you can configure a `property-placeholder` to point to the above property file, as the following example shows:
====
[source,xml]
----
<context:property-placeholder location="classpath:oauth.properties"/>
<bean id="twitterTemplate" class="o.s.social.twitter.api.impl.TwitterTemplate">
<constructor-arg value="${twitter.oauth.consumerKey}"/>
<constructor-arg value="${twitter.oauth.consumerSecret}"/>
<constructor-arg value="${twitter.oauth.accessToken}"/>
<constructor-arg value="${twitter.oauth.accessTokenSecret}"/>
</bean>
----
====
[[twitter-inbound]]
=== Twitter Inbound Adapters
Twitter inbound adapters let you receive Twitter Messages.
There are several types of http://support.twitter.com/articles/119138-types-of-tweets-and-where-they-appear[twitter messages, or tweets].
As of version 2.0, Spring Integration provides support for receiving tweets as timeline updates, direct messages, and mention messages (as well as search results).
[IMPORTANT]
=====
Every inbound Twitter channel adapter is a polling consumer, which means you have to provide a poller configuration.
Twitter uses a concept called https://dev.twitter.com/docs/rate-limiting/1.1[Rate Limiting].
In a nutshell, Twitter uses rate limiting to manage how often an application can poll for updates.
You should consider this when setting your poller intervals so that the adapter polls in compliance with Twitter policies.
With Spring Integration prior to version 3.0, a hard-coded limit within the adapters was used to ensure the polling interval could not be less than 15 seconds.
This is no longer the case, and the poller configuration is applied directly.
=====
Another issue that you need to consider is handling duplicate Tweets.
The same adapter (for example, search or timeline update), while polling on Twitter, may receive the same values more than once.
For example, if you keep searching on Twitter with the same search criteria, you end up with the same set of tweets unless some new tweet that matches your search criteria was posted in between your searches.
In that situation, you get all the tweets you had before plus the new one.
However, you really want only the new tweet.
Spring Integration provides an elegant mechanism for handling these situations.
The latest Tweet ID (the last retrieved tweet in this case) is stored in an instance of the `org.springframework.integration.metadata.MetadataStore` strategy .
For more information, see "`<<metadata-store>>`".
NOTE: The key used to persist the latest Twitter ID is the value of the (required) `id` attribute of the Twitter inbound channel adapter component plus the `profileId` of the Twitter user.
Prior to version 4.0, the page size was hard-coded to 20.
You can now configure it by using the `page-size` attribute (which defaults to 20).
[[inbound-twitter-update]]
==== Inbound Message Channel Adapter
This adapter lets you receive updates from everyone you follow.
It is essentially the "`timeline update`" adapter.
The following example configures a Twitter inbound channel adapter to poll for at most three messages every five seconds:
====
[source,xml]
----
<int-twitter:inbound-channel-adapter
twitter-template="twitterTemplate"
channel="inChannel">
<int:poller fixed-rate="5000" max-messages-per-poll="3"/>
</int-twitter:inbound-channel-adapter>
----
====
[[inbound-twitter-direct]]
==== Direct Inbound Message Channel Adapter
This adapter lets you receive direct messages that were sent to you from other Twitter users.
The following example configures a Twitter direct message inbound channel adapter to poll for at most three direct messages every five seconds:
====
[source,xml]
----
<int-twitter:dm-inbound-channel-adapter
twitter-template="twiterTemplate"
channel="inboundDmChannel">
<int-poller fixed-rate="5000" max-messages-per-poll="3"/>
</int-twitter:dm-inbound-channel-adapter>
----
====
[[inbound-twitter-mention]]
==== Mentions Inbound Message Channel Adapter
This adapter lets you receive Twitter messages that mention you when someone uses the `@user` syntax.
The following example configures a Twitter mention inbound channel adapter to poll for at most three mentions every five seconds:
====
[source,xml]
----
<int-twitter:mentions-inbound-channel-adapter
twitter-template="twiterTemplate"
channel="inboundMentionsChannel">
<int:poller fixed-rate="5000" max-messages-per-poll="3"/>
</int-twitter:mentions-inbound-channel-adapter>
----
====
[[inbound-twitter-search]]
==== Search Inbound Message Channel Adapter
This adapter lets you perform searches.
You need not define a `twitter-template`, because you can search anonymously.
However you must define a search query.
The following example configures a Twitter search inbound channel adapter that searchs for the `#springintegration` hashtag and returns at most three results every five seconds:
====
[source,xml]
----
<int-twitter:search-inbound-channel-adapter
query="#springintegration"
channel="inboundMentionsChannel">
<int:poller fixed-rate="5000" max-messages-per-poll="3"/>
</int-twitter:search-inbound-channel-adapter>
----
====
See https://dev.twitter.com/docs/using-search to learn more about Twitter queries.
The configuration of all of these adapters is similar to other inbound adapters, with one exception: Some may need to have the `twitter-template` injected.
Once received, each Twitter message is encapsulated in a Spring Integration `Message` and sent to the channel specified by the `channel` attribute.
NOTE: Currently, the payload type of any Twitter `Message` is `org.springframework.integration.twitter.core.Tweet`, which is very similar to the object with the same name in Spring Social.
As we migrate to Spring Social, we plan to depend on its API.
Some of the artifacts that we currently use are about to be obsolete.
However, we have already made sure that the impact of such migration is minimal, by aligning our API with the current state (at the time of this writing) of Spring Social.
To get the text from the `org.springframework.social.twitter.api.Tweet`, invoke the `getText()` method.
[[twitter-outbound]]
=== Twitter Outbound Adapter
Twitter outbound channel adapters let you send Twitter Messages (called tweets).
As of version 2.0, Spring Integration supports sending status update messages and direct messages.
Twitter outbound channel adapters take the `Message` payload and send it as a Twitter message.
Currently, the only supported payload type is `String`, so you should consider adding a transformer if the payload of the incoming message is not a `String`.
[[outbound-twitter-update]]
==== Twitter Outbound Update Channel Adapter
This adapter lets you send regular status updates by sending a `Message` to the channel identified by the `channel` attribute.
The following example configures a basic Twitter outbound channel adapter:
====
[source,xml]
----
<int-twitter:outbound-channel-adapter
twitter-template="twitterTemplate"
channel="twitterChannel"/>
----
====
The only extra configuration adapter requires is the `twitter-template` reference.
Starting with version 4.0, the `<int-twitter:outbound-channel-adapter>` element supports a `tweet-data-expression` attribute to populate the `TweetData` argument (see http://projects.spring.io/spring-social-twitter/[Spring Social Twitter]) by using the message as the root object of the expression evaluation context.
The result can be one of the following:
* A `String`, which is used for the `TweetData` message
* A `Tweet` object, the `text` of which is used for the `TweetData` message
* An entire `TweetData` object.
For convenience, the `TweetData` object can be built from the expression directly without needing a fully qualified class name, as the following example shows:
====
[source,xml]
----
<int-twitter:outbound-channel-adapter
twitter-template="twitterTemplate"
channel="twitterChannel"
tweet-data-expression="new TweetData(payload).withMedia(headers.media).displayCoordinates(true)/>
----
====
This allows, among other things, attaching an image to the tweet.
[[outbound-twitter-direct]]
==== Twitter Outbound Direct Message Channel Adapter
This adapter lets you send Twitter direct messages (in other words, `@user`) by simply sending a `Message` to the channel identified by the `channel` attribute.
The following example configures a basic Twitter outbound direct message channel adapter:
====
[source,xml]
----
<int-twitter:dm-outbound-channel-adapter
twitter-template="twitterTemplate"
channel="twitterChannel"/>
----
====
The only extra configuration this adapter requires is the `twitter-template` reference.
When it comes to Twitter direct messages, you must specify to whom you are sending the message (that is, the target user ID).
The Twitter outbound direct message channel adapter looks for a target user ID in the message headers under the name of `twitter_dmTargetUserId`, which is also identified by the following constant: `TwitterHeaders.DM_TARGET_USER_ID`.
So, when creating a `Message`, you need only add a value for that header, as the following example shows:
====
[source,java]
----
Message message = MessageBuilder.withPayload("hello")
.setHeader(TwitterHeaders.DM_TARGET_USER_ID, "z_oleg").build();
----
====
The preceding approach works well if you create the `Message` programmatically.
However, it is more common to provide the header value within a messaging flow.
The value can be provided by an upstream `<header-enricher>`, as the following example shows:
====
[source,xml]
----
<int:header-enricher input-channel="in" output-channel="out">
<int:header name="twitter_dmTargetUserId" value="z_oleg"/>
</int:header-enricher>
----
====
It is quite common that the value must be determined dynamically.
For those cases, you can take advantage of SpEL support within the `<header-enricher>` by using the `expression` attribute, as the following example shows:
====
[source,xml]
----
<int:header-enricher input-channel="in" output-channel="out">
<int:header name="twitter_dmTargetUserId"
expression="@twitterIdService.lookup(headers.username)"/>
</int:header-enricher>
----
====
IMPORTANT: Twitter does not let you post duplicate messages.
This is a common problem during testing, when the same code works the first time but does not work the second time.
Consequently, you need to change the content of the message each time.
Appending a timestamp to the end of each message works well for testing.
[[twitter-sog]]
=== Twitter Search Outbound Gateway
In Spring Integration, an outbound gateway is used for two-way request-response communication with an external service.
The Twitter search outbound gateway lets you issue dynamic Twitter searches.
The reply message payload is a collection of `Tweet` objects.
If the search returns no results, the payload is an empty collection.
You can limit the number of tweets, and you can page through a larger set of tweets by making multiple calls.
To facilitate this, search reply messages contain a header called `twitter_searchMetadata`.
Its value is a `SearchMetadata` object.
For more information on the `Tweet`, `SearchParameters`, and `SearchMetadata` classes, see the http://projects.spring.io/spring-social-twitter/[Spring Social Twitter] documentation.
==== Configuring the Twitter Search Outbound Gateway
The following listing shows the available attributes for a Twitter search outbound gateway:
====
[source,xml]
----
<int-twitter:search-outbound-gateway id="twitter"
request-channel="in" <1>
twitter-template="twitterTemplate" <2>
search-args-expression="payload" <3>
reply-channel="out" <4>
reply-timeout="123" <5>
order="1" <6>
auto-startup="false" <7>
phase="100" /> <8>
----
<1> The channel used to send search requests to this gateway.
<2> A reference to a `TwitterTemplate` that has authentication configuration.
<3> A SpEL expression that evaluates to the arguments for the search.
Default: *"payload"* - in which case the payload can be a `String` (such as "#springintegration"), and the gateway limits the query to 20 tweets.
Alternatively, the payload can be a `SearchParameters` object.
You can also specify the expression as a http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html#expressions-inline-lists[SpEL List].
The first element (a `String`) is the query, the remaining elements (`Number` objects) are `pageSize`, `sinceId`, and `maxId`, respectively. See the http://projects.spring.io/spring-social-twitter/[Spring Social Twitter] documentation for more information about these parameters.
When specifying a `SearchParameters` object directly in the SpEL expression, you do not have to fully qualify the class name.
The following examples all work:
+
`new SearchParameters(payload).count(5).sinceId(headers.sinceId)`
+
`{payload, 30}`
+
`{payload, headers.pageSize, headers.sinceId, headers.maxId}`
<4> The channel to which to send the reply.
If omitted, the `replyChannel` header is used.
<5> The timeout when sending the reply message to the reply channel.
It applies only if the reply channel can block (for example, a bounded queue channel that is full).
<6> When subscribed to a publish-subscribe channel, the order in which this endpoint is invoked.
<7> `SmartLifecycle` method.
<8> `SmartLifecycle` method.
====

View File

@@ -106,10 +106,15 @@ See "`<<jdbc>>`" for more information.
=== FTP and SFTP Changes
A `RotatingServerAdvice` is now available to poll multiple servers and directories with the inbound channel adapters.
See "`<<ftp-rotating-server-advice>>`" and "`<<sftp-rotating-server-advice>>`" for more information.
See <<ftp-rotating-server-advice>> and <<sftp-rotating-server-advice>> for more information.
Also, inbound adapter `localFilenameExpression` instances can contain the `#remoteDirectory` variable, which contains the remote directory being polled.
The generic type of the comparators, used to sort the fetched file list for the streaming adapters, has changed from `Comparator<AbstractFileInfo<F>>` to simply `Comparator<F>`.
See <<ftp-streaming>> and <<sftp-streaming>> for more information.
In addition, the synchronizers for inbound channel adapters can now be provided with a `Comparator`; this is useful when using `maxFetchSize` to limit the files retrieved.
==== Twitter Support
Since the Spring Social project has moved to https://spring.io/blog/2018/07/03/spring-social-end-of-life-announcement[End of Life Status], Twitter support in Spring Integration has been moved to the Extensions project.
See https://github.com/spring-projects/spring-integration-extensions/tree/master/spring-integration-social-twitter[Spring Integration Social Twitter] for more information.