Over a million developers have joined DZone.

Spring Integration with Twitter: How to Post Tweets to Your Twitter Account?

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

Spring Integration provides support for interacting with Twitter. With the Twitter adapters you can both receive and send Twitter messages.

This article provides code snippets and guidelines to post “tweets” to your Twitter account using Spring Integration module.

What you will need to run this tutorial?

  • Twitter Account
  • Twitter oAuth Keys
  • Spring Integration Module
  • Maven
  • An IDE – I am using SpringSource Tool Suite
  • Some spare time

Sign-up For a Twitter Account

Create the Twitter account that you want to use from your application. For this tutorial, I have created an account @SkilledTester.

Twitter Signup Page

Register Your Application

Log into Twitter and register a new application with Twitter at this link.

Twitter - Create an application

Fill in all the required fields and submit the request to create a new Twitter application.

You can leave the “Callaback URL” field as empty. This field is not required for standalone applications.

Once the application is successfully created, you will redirected to the Details Tab as shown below

Twitter - Application Details Page

By default, Access level for the application under OAuth settings is Read-Only. You need to change it so you can also Write and Access Direct Messages.

Click on Settings Tab | Scroll Down to Application Type section and change the access level to Read, Write and Access Direct Messages | click on Update Twitter Application Settings

Twitter - Access Level for Application

Now go back to the Details Tab and confirm that Access Level is changed  to Read, Write and Access Direct Messages.

This step might take couple of minutes to reflect the changes. Once the Access Level is updated, proceed with next steps.

Authorize Your New Application with Twitter

Now, you need to authorize your new Application to access your Twitter Account. This can be done by requesting OAuth Access Token from the Application’s Details Tab

Twitter - Request Access Token

Click on Create my access token.  This will automatically create the access token with the same permission level as of your application.

Your application is now having access to your Twitter Account. You can confirm the same by logging into your Twitter Account and under Settings go to Apps and you will see the new application that we created in the previous step.

At this point you are ready to use your OAuth Consumer Key and Consumer Secret Code along with your Access Token to post updates to your Twitter account.

Now straight into code details.

org.springframework.integration
spring-integration-twitter
2.1.3.RELEASE

Twitter Configuration Template

All the Twitter adapters require a Twitter template that will be configured using Spring Java configuration as follows -

package com.skilledmonster.spring.integration.twitter;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
 
/**
 * Spring Java Twitter Configuration Template to configure Twitter Template
 * @author Jagadeesh
 *
 */
@Configuration
public class TwitterConfigurationTemplate {
    @Value("${twitter.consumer-key}")
    private String consumerKey;
 
    @Value("${twitter.consumer-secret}")
    private String consumerSecret;
 
    @Value("${twitter.access-token}")
    private String accessToken;
 
    @Value("${twitter.access-token-secret}")
    private String accessTokenSecret;
 
    @Bean
    public TwitterTemplate twitterTemplate() {
        TwitterTemplate twitterOperations = new TwitterTemplate(consumerKey,
                consumerSecret, accessToken, accessTokenSecret);
        return twitterOperations;
    }
}

The twitterTemplate bean requires a set of authorization keys. These can be obtained by placing a request with dev.twitter.com.

Twitter Keys

The Twitter keys are defined in twitter.properties file as shown below. These keys are used to authenticate and authorize the user.

For the purpose of this example, I have posted my SkilledMonster test account authentication and authorization keys.

Account Name: @SkilledTester

Account URL: https://twitter.com/SkilledTester

Consumer key, Consumer secret, Access token and Access token secret are obtained from the Twitter Application Details Tab as already shown above.
# authentication and authorization keys for Twitter account @SkilledTester
twitter.consumer-key=K2uW4JGtng7BYMpEk9qhOw
twitter.consumer-secret=9JWmsiiPpszdKfxj4X88ZbnfX1hPhZRnnPHRxzX9hnw
twitter.access-token=792995125-Pi6u8AvH46sIqVjYTsS8fv6hnRfluSQtL2nSxNta
twitter.access-token-secret=pJtyFZP47zOmcOQQEwJUren8KbcleApRAmytAJE

Note: Please make sure not to have any empty spaces at the end of key-values.

Spring Configuration for Twitter Update Message

Using Spring Integration, a channel message may be converted into a Twitter update. The outbound-channel-adapter is configured to send the incoming channel message on twitterOutbound to Twitter as an update to @SkilledTester

twitter-outoutbound.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:twitter="http://www.springframework.org/schema/integration/twitter"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/integration/twitter
 
http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd
 
 
http://www.springframework.org/schema/beans
 
 
http://www.springframework.org/schema/beans/spring-beans-3.0.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">
 
    <context:property-placeholder location="/twitter.properties" />
 
    <int:channel id="twitterOutbound" />
 
    <twitter:outbound-channel-adapter
        twitter-template="twitterTemplate" channel="twitterOutbound" />
 
    <bean id="twitterTemplate"
        class="org.springframework.social.twitter.api.impl.TwitterTemplate">
        <constructor-arg value="${twitter.consumer-key}" />
        <constructor-arg value="${twitter.consumer-secret}" />
        <constructor-arg value="${twitter.access-token}" />
        <constructor-arg value="${twitter.access-token-secret}" />
    </bean>
 
</beans>

Note that it is also mandatory to add twitter namespace to the configuration file.

Logger Configuration

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
    <!-- Appenders -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{HH:mm:ss.SSS} %-5p [%t][%c] %m%n" />
        </layout>
    </appender>
 
    <!-- Loggers -->
    <logger name="com.skilledmonster.spring.integration.twitter">
        <level value="info" />
    </logger>
 
    <!-- Root Logger -->
    <root>
        <priority value="warn" />
        <appender-ref ref="console" />
    </root>
 
</log4j:configuration>

Test Class

I have created the following test class to test Twitter update Spring Configuration. This class simply sends a text message to the twitterOutbound message channel that will post the update to the Twitter account @SkilledTester.

package com.skilledmonster.spring.integration.twitter;
 
import java.util.Calendar;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.message.GenericMessage;
 
/**
* Sample Test Class to post an update to Twitter Account
* @author Jagadeesh
*
*/
public class TwitterOutbound {
 
    public static void main(String[] args) {
 
        ApplicationContext context = new ClassPathXmlApplicationContext("/twitter-outbound.xml", TwitterOutbound.class);
 
        MessageChannel input = context.getBean("twitterOutbound", MessageChannel.class);
 
        Message message = new GenericMessage(Calendar.getInstance().getTime()+" @ New Message from Skilled Monster using Spring Integration Module");
 
        input.send(message);
    }
}
Note that I am prefixing the message with timestamp because twitter doesn’t allow to post the same update twice in a certain time window.

Twitter Update Posted by Test Class @SkilledTester

Directory Structure



Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

Topics:

Published at DZone with permission of Jagadeesh Motamarri, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}