JAVA-15787 Created new messaging-modules and saas-modules

- Moved jgroups, rabbitmq, spring-amqp, spring-apache-camel, spring-jms to messaging-modules
- Moved twilio, twitter4j, strip to saas-modules
- Renamed existing saas to jira-rest-integration
This commit is contained in:
Dhawal Kapil
2022-11-26 11:54:53 +05:30
parent 818d181400
commit c2d6d9f695
142 changed files with 91 additions and 57 deletions

View File

@@ -0,0 +1,26 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@@ -0,0 +1,7 @@
## Jira Rest Integration
This module contains articles about Jira Rest Integration
## Relevant articles:
- [JIRA REST API Integration](https://www.baeldung.com/jira-rest-api)

View File

@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jira-rest-integration</artifactId>
<name>jira-rest-integration</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>saas-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-rest-java-client-core</artifactId>
<version>${jira-rest-java-client-core.version}</version>
</dependency>
<dependency>
<groupId>com.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>${atlassian.fugue.version}</version>
</dependency>
</dependencies>
<build>
<finalName>saas</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>atlassian-public</id>
<url>https://packages.atlassian.com/maven/repository/public</url>
</repository>
</repositories>
<properties>
<jira-rest-java-client-core.version>4.0.0</jira-rest-java-client-core.version>
<atlassian.fugue.version>2.6.1</atlassian.fugue.version>
</properties>
</project>

View File

@@ -0,0 +1,103 @@
package com.baeldung.saas.jira;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.BasicVotes;
import com.atlassian.jira.rest.client.api.domain.Comment;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.input.IssueInput;
import com.atlassian.jira.rest.client.api.domain.input.IssueInputBuilder;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class MyJiraClient {
private String username;
private String password;
private String jiraUrl;
private JiraRestClient restClient;
private MyJiraClient(String username, String password, String jiraUrl) {
this.username = username;
this.password = password;
this.jiraUrl = jiraUrl;
this.restClient = getJiraRestClient();
}
public static void main(String[] args) throws IOException {
MyJiraClient myJiraClient = new MyJiraClient("user.name", "pass", "http://jira.company.com");
final String issueKey = myJiraClient.createIssue("ABCD", 1L, "Issue created from JRJC");
myJiraClient.updateIssueDescription(issueKey, "This is description from my Jira Client");
Issue issue = myJiraClient.getIssue(issueKey);
System.out.println(issue.getDescription());
myJiraClient.voteForAnIssue(issue);
System.out.println(myJiraClient.getTotalVotesCount(issueKey));
myJiraClient.addComment(issue, "This is comment from my Jira Client");
List<Comment> comments = myJiraClient.getAllComments(issueKey);
comments.forEach(c -> System.out.println(c.getBody()));
myJiraClient.deleteIssue(issueKey, true);
myJiraClient.restClient.close();
}
private String createIssue(String projectKey, Long issueType, String issueSummary) {
IssueRestClient issueClient = restClient.getIssueClient();
IssueInput newIssue = new IssueInputBuilder(projectKey, issueType, issueSummary).build();
return issueClient.createIssue(newIssue).claim().getKey();
}
private Issue getIssue(String issueKey) {
return restClient.getIssueClient().getIssue(issueKey).claim();
}
private void voteForAnIssue(Issue issue) {
restClient.getIssueClient().vote(issue.getVotesUri()).claim();
}
private int getTotalVotesCount(String issueKey) {
BasicVotes votes = getIssue(issueKey).getVotes();
return votes == null ? 0 : votes.getVotes();
}
private void addComment(Issue issue, String commentBody) {
restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody));
}
private List<Comment> getAllComments(String issueKey) {
return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false)
.collect(Collectors.toList());
}
private void updateIssueDescription(String issueKey, String newDescription) {
IssueInput input = new IssueInputBuilder().setDescription(newDescription).build();
restClient.getIssueClient().updateIssue(issueKey, input).claim();
}
private void deleteIssue(String issueKey, boolean deleteSubtasks) {
restClient.getIssueClient().deleteIssue(issueKey, deleteSubtasks).claim();
}
private JiraRestClient getJiraRestClient() {
return new AsynchronousJiraRestClientFactory()
.createWithBasicHttpAuthentication(getJiraUri(), this.username, this.password);
}
private URI getJiraUri() {
return URI.create(this.jiraUrl);
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

36
saas-modules/pom.xml Normal file
View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>saas-modules</artifactId>
<name>saas-modules</name>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<modules>
<module>jira-rest-integration</module>
<module>stripe</module>
<module>twilio</module>
<module>twitter4j</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

27
saas-modules/stripe/.gitignore vendored Normal file
View File

@@ -0,0 +1,27 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
###
desktop.ini

View File

@@ -0,0 +1,8 @@
### Stripe
This module contains articles about Stripe
### Relevant articles
- [Introduction to the Stripe API for Java](https://www.baeldung.com/java-stripe-api)
- [Viewing Contents of a JAR File](https://www.baeldung.com/java-view-jar-contents)

View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.stripe</groupId>
<artifactId>stripe</artifactId>
<name>stripe</name>
<packaging>jar</packaging>
<description>Demo project for Stripe API</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>saas-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
<version>${stripe.version}</version>
</dependency>
</dependencies>
<properties>
<stripe.version>4.2.0</stripe.version>
</properties>
</project>

View File

@@ -0,0 +1,37 @@
package com.baeldung.stripe;
import com.baeldung.stripe.ChargeRequest.Currency;
import com.stripe.exception.StripeException;
import com.stripe.model.Charge;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
@Log
@Controller
public class ChargeController {
@Autowired
StripeService paymentsService;
@PostMapping("/charge")
public String charge(ChargeRequest chargeRequest, Model model) throws StripeException {
chargeRequest.setDescription("Example charge");
chargeRequest.setCurrency(Currency.EUR);
Charge charge = paymentsService.charge(chargeRequest);
model.addAttribute("id", charge.getId());
model.addAttribute("status", charge.getStatus());
model.addAttribute("chargeId", charge.getId());
model.addAttribute("balance_transaction", charge.getBalanceTransaction());
return "result";
}
@ExceptionHandler(StripeException.class)
public String handleError(Model model, StripeException ex) {
model.addAttribute("error", ex.getMessage());
return "result";
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.stripe;
import lombok.Data;
@Data
public class ChargeRequest {
public enum Currency {
EUR, USD;
}
private String description;
private int amount; // cents
private Currency currency;
private String stripeEmail;
private String stripeToken;
public String getDescription() {
return description;
}
public int getAmount() {
return amount;
}
public Currency getCurrency() {
return currency;
}
public String getStripeEmail() {
return stripeEmail;
}
public String getStripeToken() {
return stripeToken;
}
public void setDescription(String description) {
this.description = description;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.stripe;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class CheckoutController {
@Value("${STRIPE_PUBLIC_KEY}")
private String stripePublicKey;
@RequestMapping("/checkout")
public String checkout(Model model) {
model.addAttribute("amount", 50 * 100); // in cents
model.addAttribute("stripePublicKey", stripePublicKey);
model.addAttribute("currency", ChargeRequest.Currency.EUR);
return "checkout";
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.stripe;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StripeApplication {
public static void main(String[] args) {
SpringApplication.run(StripeApplication.class, args);
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.stripe;
import com.stripe.Stripe;
import com.stripe.exception.APIConnectionException;
import com.stripe.exception.APIException;
import com.stripe.exception.AuthenticationException;
import com.stripe.exception.CardException;
import com.stripe.exception.InvalidRequestException;
import com.stripe.model.Charge;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class StripeService {
@Value("${STRIPE_SECRET_KEY}")
String secretKey;
@PostConstruct
public void init() {
Stripe.apiKey = secretKey;
}
public Charge charge(ChargeRequest chargeRequest)
throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException {
Map<String, Object> chargeParams = new HashMap<>();
chargeParams.put("amount", chargeRequest.getAmount());
chargeParams.put("currency", chargeRequest.getCurrency());
chargeParams.put("description", chargeRequest.getDescription());
chargeParams.put("source", chargeRequest.getStripeToken());
return Charge.create(chargeParams);
}
}

View File

@@ -0,0 +1,2 @@
STRIPE_SECRET_KEY=
STRIPE_PUBLIC_KEY=

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0; url=/checkout" />
</head>
<body></body>
</html>

View File

@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xmlns:th='http://www.thymeleaf.org'>
<head>
<title>Checkout</title>
<style>
body {
font-family: 'arial';
}
#checkout-form input,
#checkout-form button {
display: block;
margin: 12px;
}
</style>
</head>
<body>
<form action='/charge' method='POST' id='checkout-form'>
<input type='hidden' th:value='${amount}' name='amount' />
<label>Price:<span th:text='${amount/100}' /></label>
<!-- NOTE: data-key/data-amount/data-currency will be rendered by Thymeleaf -->
<script
src='https://checkout.stripe.com/checkout.js'
class='stripe-button'
th:attr='data-key=${stripePublicKey},
data-amount=${amount},
data-currency=${currency}'
data-name='Baeldung'
data-description='Spring course checkout'
data-image='http://www.baeldung.com/wp-content/themes/baeldung/favicon/android-chrome-192x192.png'
data-locale='auto'
data-zip-code='false'>
</script>
</form>
</body>
</html>

View File

@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xmlns:th='http://www.thymeleaf.org'>
<head>
<title>Result</title>
</head>
<body>
<h3 th:if='${error}' th:text='${error}' style='color: red;'></h3>
<div th:unless='${error}'>
<h3 style='color: green;'>Success!</h3>
<div>Id.: <span th:text='${id}' /></div>
<div>Status: <span th:text='${status}' /></div>
<div>Charge id.: <span th:text='${chargeId}' /></div>
<div>Balance transaction id.: <span th:text='${balance_transaction}' /></div>
</div>
<a href='/checkout.html'>Checkout again</a>
</body>
</html>

View File

@@ -0,0 +1,7 @@
## Twilio
This module contains articles about Twilio
### Relevant Articles:
- [Sending SMS in Java with Twilio](https://www.baeldung.com/java-sms-twilio)

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>twilio</artifactId>
<name>twilio</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>saas-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>${twilio.version}</version>
</dependency>
</dependencies>
<properties>
<twilio.version>7.20.0</twilio.version>
</properties>
</project>

View File

@@ -0,0 +1,23 @@
package com.baeldung.twilio.sms;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
public class TwilioSmsExample {
// Find your Account Sid and Token at twilio.com/console
public static final String ACCOUNT_SID = "SID";
public static final String AUTH_TOKEN = "AUTH";
// Create a phone number in the Twilio console
public static final String TWILIO_NUMBER = "+12223334444";
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message message = Message.creator(
new PhoneNumber("+17778889999"),
new PhoneNumber(TWILIO_NUMBER),
"Sample Twilio SMS using Java")
.create();
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.twilio.sms;
import com.twilio.Twilio;
import com.twilio.converter.Promoter;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
import java.net.URI;
public class TwilioSmsMediaExample {
// Find your Account Sid and Token at twilio.com/console
public static final String ACCOUNT_SID = "SID";
public static final String AUTH_TOKEN = "AUTH";
// Create a phone number in the Twilio console
public static final String TWILIO_NUMBER = "+12223334444";
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message message = Message.creator(
new PhoneNumber("+17778889999"),
new PhoneNumber(TWILIO_NUMBER),
"Sample Twilio MMS using Java")
.setMediaUrl(
Promoter.listOfOne(
URI.create("http://www.baeldung.com/wp-content/uploads/2017/10/icon-javaseries-home.png")))
.create();
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.twilio.sms;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.rest.api.v2010.account.Message;
public class TwilioSmsStatusAsyncExample {
// Find your Account Sid and Token at twilio.com/console
public static final String ACCOUNT_SID = "SID";
public static final String AUTH_TOKEN = "AUTH";
// Create a phone number in the Twilio console
public static final String TWILIO_NUMBER = "+12223334444";
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
ListenableFuture<ResourceSet<Message>> future = Message.reader().readAsync();
Futures.addCallback(
future,
new FutureCallback<ResourceSet<Message>>() {
public void onSuccess(ResourceSet<Message> messages) {
for (Message message : messages) {
System.out.println(message.getSid() + " : " + message.getStatus());
}
}
public void onFailure(Throwable t) {
System.out.println("Failed to get message status: " + t.getMessage());
}
});
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.twilio.sms;
import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
public class TwilioSmsStatusExample {
// Find your Account Sid and Token at twilio.com/console
public static final String ACCOUNT_SID = "SID";
public static final String AUTH_TOKEN = "AUTH";
// Create a phone number in the Twilio console
public static final String TWILIO_NUMBER = "+12223334444";
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
ResourceSet<Message> messages = Message.reader().read();
for (Message message : messages) {
System.out.println(message.getSid() + " : " + message.getStatus());
}
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,7 @@
## Twitter4J
This module contains articles about Twitter4J.
### Relevant articles
- [Introduction to Twitter4J](https://www.baeldung.com/twitter4j)

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>twitter4j</artifactId>
<name>twitter4j</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>saas-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>
<version>${twitter4j-stream.version}</version>
</dependency>
</dependencies>
<properties>
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
</properties>
</project>

View File

@@ -0,0 +1,116 @@
/**
*
*/
package com.baeldung;
import java.util.List;
import java.util.stream.Collectors;
import twitter4j.DirectMessage;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Application {
public static Twitter getTwitterinstance() {
/**
* if not using properties file, we can set access token by following way
*/
// ConfigurationBuilder cb = new ConfigurationBuilder();
// cb.setDebugEnabled(true)
// .setOAuthConsumerKey("//TODO")
// .setOAuthConsumerSecret("//TODO")
// .setOAuthAccessToken("//TODO")
// .setOAuthAccessTokenSecret("//TODO");
// TwitterFactory tf = new TwitterFactory(cb.build());
// Twitter twitter = tf.getSingleton();
Twitter twitter = TwitterFactory.getSingleton();
return twitter;
}
public static String createTweet(String tweet) throws TwitterException {
Twitter twitter = getTwitterinstance();
Status status = twitter.updateStatus("creating baeldung API");
return status.getText();
}
public static List<String> getTimeLine() throws TwitterException {
Twitter twitter = getTwitterinstance();
List<Status> statuses = twitter.getHomeTimeline();
return statuses.stream().map(
item -> item.getText()).collect(
Collectors.toList());
}
public static String sendDirectMessage(String recipientName, String msg) throws TwitterException {
Twitter twitter = getTwitterinstance();
DirectMessage message = twitter.sendDirectMessage(recipientName, msg);
return message.getText();
}
public static List<String> searchtweets() throws TwitterException {
Twitter twitter = getTwitterinstance();
Query query = new Query("source:twitter4j baeldung");
QueryResult result = twitter.search(query);
List<Status> statuses = result.getTweets();
return statuses.stream().map(
item -> item.getText()).collect(
Collectors.toList());
}
public static void streamFeed() {
StatusListener listener = new StatusListener(){
@Override
public void onException(Exception e) {
e.printStackTrace();
}
@Override
public void onDeletionNotice(StatusDeletionNotice arg) {
System.out.println("Got a status deletion notice id:" + arg.getStatusId());
}
@Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
@Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
@Override
public void onStatus(Status status) {
System.out.println(status.getUser().getName() + " : " + status.getText());
}
@Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
};
TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
twitterStream.addListener(listener);
twitterStream.sample();
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,4 @@
oauth.consumerKey=//TODO
oauth.consumerSecret=//TODO
oauth.accessToken=//TODO
oauth.accessTokenSecret=//TODO

View File

@@ -0,0 +1,40 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import twitter4j.TwitterException;
public class ApplicationManualTest {
/**
* In order run this jUnit test you need to configure your API details in the twitter4j.properties
*/
String tweet = "baeldung is awsome";
@Test
public void givenText_updateStatus() throws TwitterException {
String text = Application.createTweet(tweet);
assertEquals(tweet, text);
}
@Test
public void givenCredential_fetchStatus() throws TwitterException {
List<String> statuses = Application.getTimeLine();
List<String> expectedStatuses = new ArrayList<String>();
expectedStatuses.add(tweet);
assertEquals(expectedStatuses, statuses);
}
@Test
public void givenRecipientNameAndMessage_sendDirectMessage() throws TwitterException {
String msg = Application.sendDirectMessage("YOUR_RECCIPIENT_ID", tweet);
assertEquals(msg, tweet);
}
}