diff --git a/rest-social-media/README.md b/rest-social-media/README.md new file mode 100644 index 0000000..3623dc3 --- /dev/null +++ b/rest-social-media/README.md @@ -0,0 +1,45 @@ +# Springboot and Ballerina + +A sample code base which touches key features of each technology. The sample is based on a simple API written for a social-media site which has users and associated posts. Following is the high level component diagram. + +drawing + +Following are the features used for the implementation + +1. Configuring verbs and URLs +2. Error handlers for sending customized error messages +3. Adding constraints/validations +4. OpenAPI specification for Generating API docs +5. Accessing database +6. Configurability +7. HTTP client +8. Resiliency - Retry +9. Docker image generation + +# Setting up each environment + +## Spring boot +Run the `springboot-docker-compose.yml` docker compose setup. +```sh +docker compose -f springboot-docker-compose.yml up +``` + +## Spring boot (Reactive) +Run the `springboot-reactive-docker-compose.yml` docker compose setup. +```sh +docker compose -f springboot-reactive-docker-compose.yml up +``` + +## Ballerina +Run the `ballerina-docker-compose.yml` docker compose setup. +```sh +docker compose -f ballerina-docker-compose.yml up +``` + +# Try out +## Spring boot (Default and Reactive) +- To send request open `springboot-social-media.http` file using VS Code with `REST Client` extension + +## Ballerina +- To send request open `ballerina-social-media.http` file using VS Code with `REST Client` extension + diff --git a/rest-social-media/ballerina-docker-compose.yml b/rest-social-media/ballerina-docker-compose.yml new file mode 100644 index 0000000..e6b1e2b --- /dev/null +++ b/rest-social-media/ballerina-docker-compose.yml @@ -0,0 +1,36 @@ +version: '2.14.0' + +services: + social-media: + image: 'integrationsamples/ballerina-social-media:0.0.1' + ports: + - '9090:9090' + depends_on: + sentiment-analysis: + condition: service_started + mysql: + condition: service_healthy + network_mode: "host" + + sentiment-analysis: + image: 'shafreen/ballerina-sentiment-api:0.0.1' + ports: + - '9099:9099' + network_mode: "host" + + mysql: + image: 'mysql:8-oracle' + ports: + - '3306:3306' + network_mode: "host" + environment: + - MYSQL_ROOT_PASSWORD=dummypassword + - MYSQL_DATABASE=social_media_database + - MYSQL_USER=social_media_user + - MYSQL_PASSWORD=dummypassword + healthcheck: + test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] + timeout: 20s + retries: 10 + volumes: + - "./resources/db/init.sql:/docker-entrypoint-initdb.d/1.sql" diff --git a/rest-social-media/ballerina-social-media.http b/rest-social-media/ballerina-social-media.http new file mode 100644 index 0000000..46c6f56 --- /dev/null +++ b/rest-social-media/ballerina-social-media.http @@ -0,0 +1,32 @@ +### Creat a user +POST http://localhost:9090/social-media/users +content-type: application/json + +{ + "birthDate": { + "year": 1987, + "month": 02, + "day": 06 + }, + "name": "Rimas" +} + +### Get users +GET http://localhost:9090/social-media/users + +### Get a specific user +GET http://localhost:9090/social-media/users/1 + +### Get posts +GET http://localhost:9090/social-media/users/3/posts + +### Create a post +POST http://localhost:9090/social-media/users/3/posts +content-type: application/json + +{ + "description": "I wang to learn GCP" +} + +### Delete a user +DELETE http://localhost:9090/social-media/users/1 diff --git a/rest-social-media/ballerina/Ballerina.toml b/rest-social-media/ballerina/Ballerina.toml new file mode 100644 index 0000000..735d0ef --- /dev/null +++ b/rest-social-media/ballerina/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "integration_samples" +name = "ballerina_social_media" +version = "0.0.1" +distribution = "2201.7.0" + +[build-options] +observabilityIncluded = true diff --git a/rest-social-media/ballerina/Cloud.toml b/rest-social-media/ballerina/Cloud.toml new file mode 100644 index 0000000..42ab7a2 --- /dev/null +++ b/rest-social-media/ballerina/Cloud.toml @@ -0,0 +1,8 @@ +[container.image] +repository="integrationsamples" +name="ballerina-social-media" +tag="0.0.1" + +[[container.copy.files]] +sourceFile="./Config.toml" +target="./Config.toml" diff --git a/rest-social-media/ballerina/Config.toml b/rest-social-media/ballerina/Config.toml new file mode 100644 index 0000000..2902112 --- /dev/null +++ b/rest-social-media/ballerina/Config.toml @@ -0,0 +1,8 @@ +moderate = true + +[databaseConfig] +host = "localhost" +port = 3306 +user = "social_media_user" +password = "dummypassword" +database = "social_media_database" diff --git a/rest-social-media/ballerina/response_error_interceptor.bal b/rest-social-media/ballerina/response_error_interceptor.bal new file mode 100644 index 0000000..7afbd14 --- /dev/null +++ b/rest-social-media/ballerina/response_error_interceptor.bal @@ -0,0 +1,49 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you 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. + +import ballerina/http; + +// Handle listener errors +service class ResponseErrorInterceptor { + *http:ResponseErrorInterceptor; + + remote function interceptResponseError(http:Request req, error err) + returns SocialMediaBadReqeust|SocialMediaServerError { + ErrorDetails errorDetails = buildErrorPayload(err.message(), req.rawPath); + + if err is http:PayloadValidationError { + SocialMediaBadReqeust socialMediaBadRequest = { + body: errorDetails + }; + return socialMediaBadRequest; + } else { + SocialMediaServerError socialMediaServerError = { + body: errorDetails + }; + return socialMediaServerError; + } + } +} + +type SocialMediaBadReqeust record {| + *http:BadRequest; + ErrorDetails body; +|}; + +type SocialMediaServerError record {| + *http:InternalServerError; + ErrorDetails body; +|}; diff --git a/rest-social-media/ballerina/sentiment.bal b/rest-social-media/ballerina/sentiment.bal new file mode 100644 index 0000000..6931a79 --- /dev/null +++ b/rest-social-media/ballerina/sentiment.bal @@ -0,0 +1,26 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you 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. + +type Probability record { + decimal neg; + decimal neutral; + decimal pos; +}; + +type Sentiment record { + Probability probability; + string label; +}; diff --git a/rest-social-media/ballerina/social_media_service.bal b/rest-social-media/ballerina/social_media_service.bal new file mode 100644 index 0000000..de3eea6 --- /dev/null +++ b/rest-social-media/ballerina/social_media_service.bal @@ -0,0 +1,164 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you 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. + +import ballerina/http; +import ballerina/sql; +import ballerina/mime; +import ballerinax/mysql.driver as _; +import ballerinax/mysql; +import ballerina/log; +import ballerina/time; + +configurable boolean moderate = ?; + +type DataBaseConfig record {| + string host; + int port; + string user; + string password; + string database; +|}; +configurable DataBaseConfig databaseConfig = ?; + +listener http:Listener socialMediaListener = new (9090); + +service SocialMedia /social\-media on socialMediaListener { + + final mysql:Client socialMediaDb; + final http:Client sentimentEndpoint; + + public function init() returns error? { + self.socialMediaDb = check new (...databaseConfig); + self.sentimentEndpoint = check new("localhost:9099", + retryConfig = { + interval: 3 + } + ); + log:printInfo("Social media service started"); + } + + // Service-level error interceptors can handle errors occurred during the service execution. + public function createInterceptors() returns ResponseErrorInterceptor { + return new ResponseErrorInterceptor(); + } + + # Get all the users + # + # + return - The list of users or error message + resource function get users() returns User[]|error { + stream userStream = self.socialMediaDb->query(`SELECT * FROM social_media_database.user`); + return from User user in userStream + select user; + } + + # Get a specific user + # + # + id - The user ID of the user to be retrived + # + return - A specific user or error message + resource function get users/[int id]() returns User|UserNotFound|error { + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user WHERE ID = ${id}`); + if result is sql:NoRowsError { + ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); + UserNotFound userNotFound = { + body: errorDetails + }; + return userNotFound; + } + return result; + } + + # Create a new user + # + # + newUser - The user details of the new user + # + return - The created message or error message + resource function post users(NewUser newUser) returns http:Created|error { + _ = check self.socialMediaDb->execute(` + INSERT INTO social_media_database.user(birth_date, name) + VALUES (${newUser.birthDate}, ${newUser.name});`); + return http:CREATED; + } + + # Delete a user + # + # + id - The user ID of the user to be deleted + # + return - The success message or error message + resource function delete users/[int id]() returns http:NoContent|error { + _ = check self.socialMediaDb->execute(` + DELETE FROM social_media_database.user WHERE id = ${id};`); + return http:NO_CONTENT; + } + + # Get posts for a give user + # + # + id - The user ID for which posts are retrieved + # + return - A list of posts or error message + resource function get users/[int id]/posts() returns Post[]|UserNotFound|error { + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user WHERE id = ${id}`); + if result is sql:NoRowsError { + ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); + UserNotFound userNotFound = { + body: errorDetails + }; + return userNotFound; + } + + stream postStream = self.socialMediaDb->query(`SELECT id, description FROM social_media_database.post WHERE user_id = ${id}`); + Post[]|error posts = from Post post in postStream + select post; + return posts; + } + + # Create a post for a given user + # + # + id - The user ID for which the post is created + # + return - The created message or error message + resource function post users/[int id]/posts(NewPost newPost) returns http:Created|UserNotFound|PostForbidden|error { + User|error result = self.socialMediaDb->queryRow(`SELECT * FROM social_media_database.user WHERE id = ${id}`); + if result is sql:NoRowsError { + ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); + UserNotFound userNotFound = { + body: errorDetails + }; + return userNotFound; + } + + Sentiment sentiment = check self.sentimentEndpoint->/text\-processing/api/sentiment.post( + { text: newPost }, + mediatype = mime:APPLICATION_FORM_URLENCODED + ); + if sentiment.label == "neg" { + ErrorDetails errorDetails = buildErrorPayload(string `id: ${id}`, string `users/${id}/posts`); + PostForbidden postForbidden = { + body: errorDetails + }; + return postForbidden; + } + + _ = check self.socialMediaDb->execute(` + INSERT INTO social_media_database.post(description, user_id) + VALUES (${newPost.description}, ${id});`); + return http:CREATED; + } +} + +function buildErrorPayload(string msg, string path) returns ErrorDetails { + ErrorDetails errorDetails = { + message: msg, + timeStamp: time:utcNow(), + details: string `uri=${path}` + }; + return errorDetails; +} diff --git a/rest-social-media/ballerina/social_media_service_desc.bal b/rest-social-media/ballerina/social_media_service_desc.bal new file mode 100644 index 0000000..a3c21c4 --- /dev/null +++ b/rest-social-media/ballerina/social_media_service_desc.bal @@ -0,0 +1,76 @@ +// Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. +// +// WSO2 LLC. licenses this file to you 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. + +import ballerina/constraint; +import ballerina/http; +import ballerina/sql; +import ballerina/time; + +type SocialMedia service object { + *http:InterceptableService; + + // users resource + resource function get users() returns User[]|error; + resource function get users/[int id]() returns User|UserNotFound|error; + resource function post users(NewUser newUser) returns http:Created|error; + resource function delete users/[int id]() returns http:NoContent|error; + + // posts resource + resource function get users/[int id]/posts() returns Post[]|UserNotFound|error; + resource function post users/[int id]/posts(NewPost newPost) returns http:Created|UserNotFound|PostForbidden|error; +}; + +// user representations +type User record {| + int id; + string name; + @sql:Column {name: "birth_date"} + time:Date birthDate; +|}; + +public type NewUser record {| + @constraint:String { + minLength: 2 + } + string name; + time:Date birthDate; +|}; + +type UserNotFound record {| + *http:NotFound; + ErrorDetails body; +|}; + +// post representations +type Post record {| + int id; + string description; +|}; + +public type NewPost record {| + string description; +|}; + +type PostForbidden record {| + *http:Forbidden; + ErrorDetails body; +|}; + +type ErrorDetails record {| + time:Utc timeStamp; + string message; + string details; +|}; diff --git a/rest-social-media/resources/db/init.sql b/rest-social-media/resources/db/init.sql new file mode 100644 index 0000000..30d7df5 --- /dev/null +++ b/rest-social-media/resources/db/init.sql @@ -0,0 +1,31 @@ +CREATE TABLE user ( + id INT NOT NULL auto_increment PRIMARY KEY, + birth_date DATE, + name VARCHAR(255) +); +CREATE TABLE post ( + id INT NOT NULL auto_increment PRIMARY KEY, + description VARCHAR(255), + user_id INT +); + +insert into user(birth_date, name) +values(current_date(), 'Ranga'); + +insert into user(birth_date, name) +values(current_date(), 'Ravi'); + +insert into user(birth_date, name) +values(current_date(), 'Sathish'); + +insert into post(description, user_id) +values('I want to learn AWS', 1); + +insert into post(description, user_id) +values('I want to learn DevOps', 1); + +insert into post(description, user_id) +values('I want to learn GCP', 2); + +insert into post(description, user_id) +values('I want to learn multi cloud', 3); diff --git a/rest-social-media/springboot-and-ballerina.png b/rest-social-media/springboot-and-ballerina.png new file mode 100644 index 0000000..048047f Binary files /dev/null and b/rest-social-media/springboot-and-ballerina.png differ diff --git a/rest-social-media/springboot-docker-compose.yml b/rest-social-media/springboot-docker-compose.yml new file mode 100644 index 0000000..27b696a --- /dev/null +++ b/rest-social-media/springboot-docker-compose.yml @@ -0,0 +1,45 @@ +version: '2.14.0' + +services: + social-media: + image: 'integrationsamples/springboot-social-media:0.0.1' + ports: + - '8087:8087' + depends_on: + sentiment-analysis: + condition: service_started + mysql: + condition: service_healthy + network_mode: "host" + + sentiment-analysis: + image: 'shafreen/springboot-sentiment-api:0.0.1' + ports: + - '8088:8088' + depends_on: + zipkin: + condition: service_started + network_mode: "host" + + zipkin: + image: 'openzipkin/zipkin' + ports: + - '9411:9411' + network_mode: "host" + + mysql: + image: 'mysql:8-oracle' + ports: + - '3306:3306' + network_mode: "host" + environment: + - MYSQL_ROOT_PASSWORD=dummypassword + - MYSQL_DATABASE=social_media_database + - MYSQL_USER=social_media_user + - MYSQL_PASSWORD=dummypassword + healthcheck: + test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] + timeout: 20s + retries: 10 + volumes: + - "./resources/db/init.sql:/docker-entrypoint-initdb.d/1.sql" diff --git a/rest-social-media/springboot-reactive-docker-compose.yml b/rest-social-media/springboot-reactive-docker-compose.yml new file mode 100644 index 0000000..290f805 --- /dev/null +++ b/rest-social-media/springboot-reactive-docker-compose.yml @@ -0,0 +1,45 @@ +version: '2.14.0' + +services: + social-media: + image: 'integrationsamples/springboot-reactive-social-media:0.0.1' + ports: + - '8087:8087' + depends_on: + sentiment-analysis: + condition: service_started + mysql: + condition: service_healthy + network_mode: "host" + + sentiment-analysis: + image: 'shafreen/springboot-sentiment-api:0.0.1' + ports: + - '8088:8088' + depends_on: + zipkin: + condition: service_started + network_mode: "host" + + zipkin: + image: 'openzipkin/zipkin' + ports: + - '9411:9411' + network_mode: "host" + + mysql: + image: 'mysql:8-oracle' + ports: + - '3306:3306' + network_mode: "host" + environment: + - MYSQL_ROOT_PASSWORD=dummypassword + - MYSQL_DATABASE=social_media_database + - MYSQL_USER=social_media_user + - MYSQL_PASSWORD=dummypassword + healthcheck: + test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] + timeout: 20s + retries: 10 + volumes: + - "./resources/db/init.sql:/docker-entrypoint-initdb.d/1.sql" diff --git a/rest-social-media/springboot-reactive/mvnw b/rest-social-media/springboot-reactive/mvnw new file mode 100755 index 0000000..66df285 --- /dev/null +++ b/rest-social-media/springboot-reactive/mvnw @@ -0,0 +1,308 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# https://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "$(uname)" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin ; then + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" + else + javaExecutable="$(readlink -f "\"$javaExecutable\"")" + fi + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$(cd "$wdir/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +fi + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/rest-social-media/springboot-reactive/mvnw.cmd b/rest-social-media/springboot-reactive/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/rest-social-media/springboot-reactive/mvnw.cmd @@ -0,0 +1,205 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/rest-social-media/springboot-reactive/pom.xml b/rest-social-media/springboot-reactive/pom.xml new file mode 100644 index 0000000..ed2a0f9 --- /dev/null +++ b/rest-social-media/springboot-reactive/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.1 + + + + integration.samples.springboot.reactive + social-media + 0.0.1-SNAPSHOT + social-media + Demo social media service using Spring Boot + + + 17 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springdoc + springdoc-openapi-webflux-ui + 1.7.0 + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-data-r2dbc + + + io.asyncer + r2dbc-mysql + 1.0.2 + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + + + + + org.graalvm.buildtools + native-maven-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + integrationsamples/springboot-reactive-${project.artifactId}:0.0.1 + + IF_NOT_PRESENT + + + + + diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplication.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplication.java new file mode 100644 index 0000000..8c1d3af --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplication.java @@ -0,0 +1,13 @@ +package integration.samples.springboot.reactive.socialmedia; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SocialMediaApplication { + + public static void main(String[] args) { + SpringApplication.run(SocialMediaApplication.class, args); + } + +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/controller/SocialMediaController.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/controller/SocialMediaController.java new file mode 100644 index 0000000..1261968 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/controller/SocialMediaController.java @@ -0,0 +1,213 @@ +package integration.samples.springboot.reactive.socialmedia.controller; + +import integration.samples.springboot.reactive.socialmedia.exception.ErrorDetails; +import integration.samples.springboot.reactive.socialmedia.exception.NegativeSentimentException; +import integration.samples.springboot.reactive.socialmedia.exception.UserNotFoundException; +import integration.samples.springboot.reactive.socialmedia.model.Post; +import integration.samples.springboot.reactive.socialmedia.model.User; +import integration.samples.springboot.reactive.socialmedia.repository.PostRepository; +import integration.samples.springboot.reactive.socialmedia.repository.UserRepository; +import integration.samples.springboot.reactive.socialmedia.sentiment.SentimentAnalysisClient; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; + +@RestController +@RequestMapping("/social-media/users") +public class SocialMediaController { + private final UserRepository userRepository; + private final PostRepository postRepository; + private final SentimentAnalysisClient sentimentAnalysisClient; + + @Value("${sentiment.moderate}") + private boolean moderate; + + @Autowired + public SocialMediaController(UserRepository userRepository, PostRepository postRepository, + SentimentAnalysisClient sentimentAnalysisClient) { + this.userRepository = userRepository; + this.postRepository = postRepository; + this.sentimentAnalysisClient = sentimentAnalysisClient; + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get users", + content = { + @Content( + mediaType = "application/json", + array = @ArraySchema( + schema = @Schema(implementation = User.class) + ) + ) + }) + }) + @GetMapping + public Flux retrieveAllUsers() { + return userRepository.findAll(); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get user", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = User.class) + ) + }), + @ApiResponse( + responseCode = "404", + description = "User not found", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @GetMapping("/{id}") + public Mono retrieveUser(@PathVariable long id) { + return userRepository + .findById(id) + .switchIfEmpty( + Mono.error(new UserNotFoundException(String.format("User not found for id: %d", id))) + ); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", + description = "Create user", + content = { + @Content( + mediaType = "application/json" + ) + }), + @ApiResponse( + responseCode = "400", + description = "Bad request", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @PostMapping + public Mono> createUser(@Valid @RequestBody User user) { + return userRepository + .save(user) + .map(savedUser -> ResponseEntity.created(null).build()); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Delete user") + }) + @DeleteMapping("/{id}") + public Mono> deleteUser(@PathVariable long id) { + return userRepository + .deleteById(id) + .map(v -> ResponseEntity.noContent().build()); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get user posts", + content = { + @Content( + mediaType = "application/json", + array = @ArraySchema( + schema = @Schema(implementation = Post.class) + ) + ) + }), + @ApiResponse( + responseCode = "404", + description = "User not found", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @GetMapping("/{id}/posts") + public Flux retrieveUserPosts(@PathVariable long id) { + return userRepository + .findById(id) + .switchIfEmpty( + Mono.error(new UserNotFoundException(String.format("User not found for id: %d", id))) + ).flatMapMany(user -> postRepository.findPostForUser(id)); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "201", + description = "Create user post", + content = { + @Content( + mediaType = "application/json" + ) + }), + @ApiResponse( + responseCode = "404", + description = "User not found", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }), + @ApiResponse( + responseCode = "400", + description = "Bad request", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @PostMapping("/{id}/posts") + public Mono> createUserPost(@PathVariable int id, @Valid @RequestBody Post post) { + return userRepository + .findById(id) + .switchIfEmpty( + Mono.error(new UserNotFoundException(String.format("User not found for id: %d", id))) + ).flatMap(user -> moderateContent(post)) + .flatMap(moderatedPost -> postRepository.save(id, post)) + .map(savedPost -> ResponseEntity.created(null).build()); + } + + private Mono moderateContent(Post post) { + if (!moderate) { + return Mono.just(post); + } + return sentimentAnalysisClient + .retrieveSentiment(post.getDescription()) + .map(sentiment -> !sentiment.getLabel().equalsIgnoreCase("neg")) + .switchIfEmpty(Mono.error(new NegativeSentimentException("Negative sentiment detected"))) + .map(sentiment -> post); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/AppExceptionalHandler.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/AppExceptionalHandler.java new file mode 100644 index 0000000..2819bf2 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/AppExceptionalHandler.java @@ -0,0 +1,39 @@ +package integration.samples.springboot.reactive.socialmedia.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.bind.support.WebExchangeBindException; + +import java.util.Map; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class AppExceptionalHandler { + + @ExceptionHandler(UserNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + ErrorDetails onUserNotFound(UserNotFoundException userNotFound, ServerHttpRequest request) { + return new ErrorDetails(userNotFound.getMessage(), Map.of("uri", request.getURI().getPath())); + } + + @ExceptionHandler(NegativeSentimentException.class) + @ResponseStatus(HttpStatus.FORBIDDEN) + ErrorDetails onNegativeSentiment(NegativeSentimentException negativeSentiment, ServerHttpRequest request) { + return new ErrorDetails(negativeSentiment.getMessage(), Map.of("uri", request.getURI().getPath())); + } + + @ExceptionHandler(WebExchangeBindException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + ErrorDetails onMethodArgumentNotValid(WebExchangeBindException webExchangeBindException, + ServerHttpRequest request) { + return new ErrorDetails("Request validation failed", Map.of( + "uri", request.getURI().getPath(), + "failedValidations", webExchangeBindException.getFieldErrors().stream() + .map(fe -> Map.of(fe.getField(), fe.getDefaultMessage())) + .collect(Collectors.toList()) + )); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/ErrorDetails.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/ErrorDetails.java new file mode 100644 index 0000000..c671219 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/ErrorDetails.java @@ -0,0 +1,28 @@ +package integration.samples.springboot.reactive.socialmedia.exception; + +import java.time.LocalDateTime; +import java.util.Map; + +public class ErrorDetails { + private final LocalDateTime timeStamp; + private final String message; + private final Map details; + + public ErrorDetails(String message, Map details) { + this.timeStamp = LocalDateTime.now(); + this.message = message; + this.details = details; + } + + public LocalDateTime getTimeStamp() { + return timeStamp; + } + + public String getMessage() { + return message; + } + + public Map getDetails() { + return details; + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/NegativeSentimentException.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/NegativeSentimentException.java new file mode 100644 index 0000000..8ebcd30 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/NegativeSentimentException.java @@ -0,0 +1,7 @@ +package integration.samples.springboot.reactive.socialmedia.exception; + +public class NegativeSentimentException extends RuntimeException { + public NegativeSentimentException(String message) { + super(message); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/UserNotFoundException.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/UserNotFoundException.java new file mode 100644 index 0000000..4eba5cf --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/exception/UserNotFoundException.java @@ -0,0 +1,7 @@ +package integration.samples.springboot.reactive.socialmedia.exception; + +public class UserNotFoundException extends RuntimeException { + public UserNotFoundException(String message) { + super(message); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/Post.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/Post.java new file mode 100644 index 0000000..26c40bc --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/Post.java @@ -0,0 +1,35 @@ +package integration.samples.springboot.reactive.socialmedia.model; + +import org.springframework.data.annotation.Id; + +public class Post { + @Id + private long id; + + private String description; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("Post{"); + sb.append("id=").append(id); + sb.append(", description='").append(description).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/User.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/User.java new file mode 100644 index 0000000..5560076 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/model/User.java @@ -0,0 +1,51 @@ +package integration.samples.springboot.reactive.socialmedia.model; + +import jakarta.validation.constraints.Past; +import jakarta.validation.constraints.Size; +import org.springframework.data.annotation.Id; + +import java.time.LocalDate; + +public class User { + @Id + private long id; + @Size(min = 2, message = "Name should have at least two characters") + private String name; + + @Past(message = "Birthdate should be in the past") + private LocalDate birthDate; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public LocalDate getBirthDate() { + return birthDate; + } + + public void setBirthDate(LocalDate birthDate) { + this.birthDate = birthDate; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("User{"); + sb.append("id=").append(id); + sb.append(", name='").append(name).append('\''); + sb.append(", birthDate=").append(birthDate); + sb.append('}'); + return sb.toString(); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/PostRepository.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/PostRepository.java new file mode 100644 index 0000000..ca0bca4 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/PostRepository.java @@ -0,0 +1,10 @@ +package integration.samples.springboot.reactive.socialmedia.repository; + +import integration.samples.springboot.reactive.socialmedia.model.Post; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public interface PostRepository { + Flux findPostForUser(long userId); + Mono save(long userId, Post post); +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/UserRepository.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/UserRepository.java new file mode 100644 index 0000000..5fb2da0 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/UserRepository.java @@ -0,0 +1,15 @@ +package integration.samples.springboot.reactive.socialmedia.repository; + +import integration.samples.springboot.reactive.socialmedia.model.User; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public interface UserRepository { + Flux findAll(); + + Mono save(User user); + + Mono findById(long id); + + Mono deleteById(long id); +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/PostRepositoryImpl.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/PostRepositoryImpl.java new file mode 100644 index 0000000..7f832c5 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/PostRepositoryImpl.java @@ -0,0 +1,52 @@ +package integration.samples.springboot.reactive.socialmedia.repository.impl; + +import integration.samples.springboot.reactive.socialmedia.model.Post; +import integration.samples.springboot.reactive.socialmedia.repository.PostRepository; +import io.r2dbc.spi.Row; +import io.r2dbc.spi.RowMetadata; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.r2dbc.core.DatabaseClient; +import org.springframework.stereotype.Repository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.function.BiFunction; + +@Repository +public class PostRepositoryImpl implements PostRepository { + private static final BiFunction MAPPING_FUNCTION = (row, rowMetadata) -> { + Post post = new Post(); + post.setId(row.get("id", Long.class)); + post.setDescription(row.get("description", String.class)); + return post; + }; + + private final DatabaseClient dbClient; + + @Autowired + public PostRepositoryImpl(DatabaseClient dbClient) { + this.dbClient = dbClient; + } + + @Override + public Flux findPostForUser(long userId) { + return dbClient.sql("SELECT * FROM post WHERE user_id=:userId") + .bind("userId", userId) + .map(MAPPING_FUNCTION) + .all(); + } + + @Override + public Mono save(long userId, Post post) { + return dbClient.sql("INSERT INTO post (description, user_id) VALUES (:description, :userId)") + .filter((statement, next) -> statement.returnGeneratedValues("id").execute()) + .bind("userId", userId) + .bind("description", post.getDescription()) + .fetch() + .first() + .map(row -> { + post.setId((long) row.get("id")); + return post; + }); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/UserRepositoryImpl.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/UserRepositoryImpl.java new file mode 100644 index 0000000..5669069 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/repository/impl/UserRepositoryImpl.java @@ -0,0 +1,69 @@ +package integration.samples.springboot.reactive.socialmedia.repository.impl; + +import integration.samples.springboot.reactive.socialmedia.model.User; +import integration.samples.springboot.reactive.socialmedia.repository.UserRepository; +import io.r2dbc.spi.Row; +import io.r2dbc.spi.RowMetadata; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.r2dbc.core.DatabaseClient; +import org.springframework.stereotype.Repository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.LocalDate; +import java.util.function.BiFunction; + +@Repository +public class UserRepositoryImpl implements UserRepository { + private static final BiFunction MAPPING_FUNCTION = (row, rowMetadata) -> { + User user = new User(); + user.setId(row.get("id", Long.class)); + user.setName(row.get("name", String.class)); + user.setBirthDate(row.get("birth_date", LocalDate.class)); + return user; + }; + + private final DatabaseClient dbClient; + + @Autowired + public UserRepositoryImpl(DatabaseClient dbClient) { + this.dbClient = dbClient; + } + + @Override + public Flux findAll() { + return dbClient.sql("SELECT * FROM user") + .map(MAPPING_FUNCTION) + .all(); + } + + @Override + public Mono save(User user) { + return dbClient.sql("INSERT INTO user (name, birth_date) VALUES (:name, :birthDate)") + .filter((statement, next) -> statement.returnGeneratedValues("id").execute()) + .bind("name", user.getName()) + .bind("birthDate", user.getBirthDate()) + .fetch() + .first() + .map(row -> { + user.setId((long) row.get("id")); + return user; + }); + } + + @Override + public Mono findById(long id) { + return dbClient.sql("SELECT * FROM user WHERE id=:userId") + .bind("userId", id) + .map(MAPPING_FUNCTION) + .first(); + } + + @Override + public Mono deleteById(long id) { + return dbClient.sql("DELETE FROM user WHERE id=:userId") + .bind("userId", id) + .fetch() + .rowsUpdated(); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Probability.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Probability.java new file mode 100644 index 0000000..7b6041f --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Probability.java @@ -0,0 +1,31 @@ +package integration.samples.springboot.reactive.socialmedia.sentiment; + +public class Probability { + private double neg; + private double neutral; + private double pos; + + public double getNeg() { + return neg; + } + + public void setNeg(double neg) { + this.neg = neg; + } + + public double getNeutral() { + return neutral; + } + + public void setNeutral(double neutral) { + this.neutral = neutral; + } + + public double getPos() { + return pos; + } + + public void setPos(double pos) { + this.pos = pos; + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Sentiment.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Sentiment.java new file mode 100644 index 0000000..af11c53 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/Sentiment.java @@ -0,0 +1,22 @@ +package integration.samples.springboot.reactive.socialmedia.sentiment; + +public class Sentiment { + private Probability probability; + private String label; + + public Probability getProbability() { + return probability; + } + + public void setProbability(Probability probability) { + this.probability = probability; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClient.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClient.java new file mode 100644 index 0000000..337d442 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClient.java @@ -0,0 +1,8 @@ +package integration.samples.springboot.reactive.socialmedia.sentiment; + +import reactor.core.publisher.Mono; + +public interface SentimentAnalysisClient { + + Mono retrieveSentiment(String content); +} diff --git a/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java new file mode 100644 index 0000000..3a6628d --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/java/integration/samples/springboot/reactive/socialmedia/sentiment/SentimentAnalysisClientImpl.java @@ -0,0 +1,38 @@ +package integration.samples.springboot.reactive.socialmedia.sentiment; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; +import reactor.util.retry.Retry; + +import java.time.Duration; + +@Service +public class SentimentAnalysisClientImpl implements SentimentAnalysisClient { + private final WebClient sentimentClient; + + @Value("${sentiment-api.maxRetryAttempts}") + private int maxRetryAttempts; + @Value("${sentiment-api.waitDuration}") + private int waitDuration; + + @Autowired + public SentimentAnalysisClientImpl() { + this.sentimentClient = WebClient.builder().baseUrl("http://localhost:8088").build(); + } + + @Override + public Mono retrieveSentiment(String content) { + return sentimentClient.post() + .uri("/text-processing/api/sentiment") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(BodyInserters.fromValue(content)) + .retrieve() + .bodyToMono(Sentiment.class) + .retryWhen(Retry.fixedDelay(maxRetryAttempts, Duration.ofSeconds(waitDuration))); + } +} diff --git a/rest-social-media/springboot-reactive/src/main/resources/application.properties b/rest-social-media/springboot-reactive/src/main/resources/application.properties new file mode 100644 index 0000000..2cf07e9 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/main/resources/application.properties @@ -0,0 +1,11 @@ +server.port=8087 + +spring.r2dbc.url=r2dbc:mysql://localhost:3306/social_media_database +spring.r2dbc.username=social_media_user +spring.r2dbc.password=dummypassword + +sentiment.moderate=true + +sentiment-api.maxRetryAttempts=3 +sentiment-api.waitDuration=5 + diff --git a/rest-social-media/springboot-reactive/src/test/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplicationTests.java b/rest-social-media/springboot-reactive/src/test/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplicationTests.java new file mode 100644 index 0000000..f7c3ee8 --- /dev/null +++ b/rest-social-media/springboot-reactive/src/test/java/integration/samples/springboot/reactive/socialmedia/SocialMediaApplicationTests.java @@ -0,0 +1,13 @@ +package integration.samples.springboot.reactive.socialmedia; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SocialMediaApplicationTests { + + // @Test + // void contextLoads() { + // } + +} diff --git a/rest-social-media/springboot-social-media.http b/rest-social-media/springboot-social-media.http new file mode 100644 index 0000000..9c89fec --- /dev/null +++ b/rest-social-media/springboot-social-media.http @@ -0,0 +1,29 @@ +### Creat a user +POST http://localhost:8087/social-media/users +content-type: application/json + +{ + "name": "Ravi", + "birthDate": "1997-08-11" +} + +### Get users +GET http://localhost:8087/social-media/users + +### Get a specific user +GET http://localhost:8087/social-media/users/1 + +### Create a post +POST http://localhost:8087/social-media/users/1/posts +content-type: application/json + +{ + "description": "I wang to learn GCP" +} + +### Get posts +GET http://localhost:8087/social-media/users/1/posts + + +### Delete a user +DELETE http://localhost:8087/social-media/users/1 \ No newline at end of file diff --git a/rest-social-media/springboot/mvnw b/rest-social-media/springboot/mvnw new file mode 100755 index 0000000..66df285 --- /dev/null +++ b/rest-social-media/springboot/mvnw @@ -0,0 +1,308 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# https://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "$(uname)" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin ; then + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" + else + javaExecutable="$(readlink -f "\"$javaExecutable\"")" + fi + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$(cd "$wdir/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +fi + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/rest-social-media/springboot/mvnw.cmd b/rest-social-media/springboot/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/rest-social-media/springboot/mvnw.cmd @@ -0,0 +1,205 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/rest-social-media/springboot/pom.xml b/rest-social-media/springboot/pom.xml new file mode 100644 index 0000000..3896968 --- /dev/null +++ b/rest-social-media/springboot/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.1 + + + + integration.samples.springboot + social-media + 0.0.1-SNAPSHOT + social-media + + Demo social media service using Spring Boot + + + 17 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-validation + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + io.github.resilience4j + resilience4j-spring-boot2 + 2.1.0 + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.1.0 + + + + org.springframework.cloud + spring-cloud-starter-openfeign + 4.0.3 + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + + mysql + mysql-connector-java + 8.0.33 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.graalvm.buildtools + native-maven-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + integrationsamples/springboot-${project.artifactId}:0.0.1 + + IF_NOT_PRESENT + + + + + diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java new file mode 100644 index 0000000..d28b3d5 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/SocialMediaApplication.java @@ -0,0 +1,15 @@ +package integration.samples.springboot.socialmedia; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@SpringBootApplication +@EnableFeignClients +public class SocialMediaApplication { + + public static void main(String[] args) { + SpringApplication.run(SocialMediaApplication.class, args); + } + +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java new file mode 100644 index 0000000..d342d68 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/controller/SocialMediaController.java @@ -0,0 +1,167 @@ +package integration.samples.springboot.socialmedia.controller; + +import integration.samples.springboot.socialmedia.exception.ErrorDetails; +import integration.samples.springboot.socialmedia.exception.NegativeSentimentException; +import integration.samples.springboot.socialmedia.exception.UserNotFoundException; +import integration.samples.springboot.socialmedia.model.Post; +import integration.samples.springboot.socialmedia.model.User; +import integration.samples.springboot.socialmedia.repository.PostRepository; +import integration.samples.springboot.socialmedia.repository.UserRepository; +import integration.samples.springboot.socialmedia.sentiment.Sentiment; +import integration.samples.springboot.socialmedia.sentiment.SentimentProxy; +import integration.samples.springboot.socialmedia.sentiment.SentimentRequest; +import io.github.resilience4j.retry.annotation.Retry; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Optional; + +@RestController +public class SocialMediaController { + + private final UserRepository userRepository; + private final PostRepository postRepository; + private final SentimentProxy sentimentProxy; + + @Value("${sentiment.moderate}") + private boolean moderate; + + @Autowired + public SocialMediaController(UserRepository userRepository, + PostRepository postRepository, + SentimentProxy sentimentProxy) { + this.userRepository = userRepository; + this.postRepository = postRepository; + this.sentimentProxy = sentimentProxy; + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get users", + content = { + @Content( + mediaType = "application/json", + array = @ArraySchema( + schema = @Schema(implementation = User.class) + ) + ) + }) + }) + @GetMapping("/social-media/users") + public List retrieveAllUsers() { + return userRepository.findAll(); + } + + @ApiResponses(value = { + @ApiResponse( + responseCode = "200", + description = "Get user", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = User.class) + ) + }), + @ApiResponse( + responseCode = "404", + description = "User not found", + content = { + @Content( + mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class) + ) + }) + }) + @GetMapping("/social-media/users/{id}") + public User retrieveUser(@PathVariable int id) { + Optional user = userRepository.findById(id); + + if (user.isEmpty()) + throw new UserNotFoundException("id: " + id); + + return user.get(); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Create user", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = User.class))}), + @ApiResponse(responseCode = "400", description = "Bad request", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class))}) + }) + @PostMapping("/social-media/users") + public ResponseEntity createUser(@Valid @RequestBody User user) { + userRepository.save(user); + return ResponseEntity.created(null).build(); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Delete user") + }) + @DeleteMapping("/social-media/users/{id}") + public void deleteUser(@PathVariable int id) { + userRepository.deleteById(id); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Create post", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = Post.class))}), + @ApiResponse(responseCode = "404", description = "User not found", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class))})}) + @GetMapping("/social-media/users/{id}/posts") + public List retrieveUserPosts(@PathVariable int id) { + Optional user = userRepository.findById(id); + + if (user.isEmpty()) + throw new UserNotFoundException("id: " + id); + + return user.get().getPosts(); + } + + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "Create post", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = User.class))}), + @ApiResponse(responseCode = "403", description = "Negative sentiment detected", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class))}), + @ApiResponse(responseCode = "404", description = "User not found", + content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorDetails.class))}) + }) + @PostMapping("/social-media/users/{id}/posts") + @Retry(name = "sentiment-api") + public ResponseEntity createUserPost(@PathVariable int id, @Valid @RequestBody Post post) { + Optional user = userRepository.findById(id); + if (user.isEmpty()) { + throw new UserNotFoundException("id: " + id); + } + if (moderate) { + Sentiment sentiment = sentimentProxy.retrieveSentiment(new SentimentRequest(post.getDescription())); + if (sentiment.getLabel().equalsIgnoreCase("neg")) { + throw new NegativeSentimentException("Negative sentiment detected"); + } + } + post.setUser(user.get()); + postRepository.save(post); + return ResponseEntity.created(null).build(); + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/AppExceptionalHandler.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/AppExceptionalHandler.java new file mode 100644 index 0000000..fcdbe6d --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/AppExceptionalHandler.java @@ -0,0 +1,36 @@ +package integration.samples.springboot.socialmedia.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; + +@RestControllerAdvice +public class AppExceptionalHandler { + + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + ErrorDetails handleAllException(Exception exception, WebRequest request) { + return new ErrorDetails(exception.getMessage(), request.getDescription(false)); + } + + @ExceptionHandler(UserNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + ErrorDetails handleUserNotFoundException(Exception userNotFound, WebRequest request) { + return new ErrorDetails(userNotFound.getMessage(), request.getDescription(false)); + } + + @ExceptionHandler(NegativeSentimentException.class) + @ResponseStatus(HttpStatus.FORBIDDEN) + ErrorDetails handleNegativeSentimentException(Exception negativeSentiment, WebRequest request) { + return new ErrorDetails(negativeSentiment.getMessage(), request.getDescription(false)); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + ErrorDetails handleMethodArgumentNotValid(MethodArgumentNotValidException methodArgNotvalid, WebRequest request) { + return new ErrorDetails(methodArgNotvalid.getMessage(), request.getDescription(false)); + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/ErrorDetails.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/ErrorDetails.java new file mode 100644 index 0000000..cea6061 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/ErrorDetails.java @@ -0,0 +1,28 @@ +package integration.samples.springboot.socialmedia.exception; + +import java.time.LocalDateTime; + +public class ErrorDetails { + + private LocalDateTime timeStamp; + private String message; + private String details; + + public ErrorDetails(String message, String details) { + this.timeStamp = LocalDateTime.now(); + this.message = message; + this.details = details; + } + + public LocalDateTime getTimeStamp() { + return timeStamp; + } + + public String getMessage() { + return message; + } + + public String getDetails() { + return details; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/NegativeSentimentException.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/NegativeSentimentException.java new file mode 100644 index 0000000..9dcc0ef --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/NegativeSentimentException.java @@ -0,0 +1,8 @@ +package integration.samples.springboot.socialmedia.exception; + +public class NegativeSentimentException extends RuntimeException { + + public NegativeSentimentException(String message) { + super(message); + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/UserNotFoundException.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/UserNotFoundException.java new file mode 100644 index 0000000..fce7f4a --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/exception/UserNotFoundException.java @@ -0,0 +1,8 @@ +package integration.samples.springboot.socialmedia.exception; + +public class UserNotFoundException extends RuntimeException { + + public UserNotFoundException(String message) { + super(message); + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/Post.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/Post.java new file mode 100644 index 0000000..6f78bd1 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/Post.java @@ -0,0 +1,47 @@ +package integration.samples.springboot.socialmedia.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; + +@Entity +public class Post { + + @Id + @GeneratedValue + private int id; + + private String description; + + @ManyToOne(fetch = FetchType.LAZY) + @JsonIgnore + private User user; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + @Override + public String toString() { + return "Post{" + "id=" + id + ", description='" + description + '\'' + '}'; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java new file mode 100644 index 0000000..f7e4bf8 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/model/User.java @@ -0,0 +1,71 @@ +package integration.samples.springboot.socialmedia.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.Past; +import jakarta.validation.constraints.Size; + +import java.time.LocalDate; +import java.util.List; + +@Entity +public class User { + + @Id + @GeneratedValue + private int id; + @Size(min = 2, message = "Name should have at least two characters") + private String name; + + @Past(message = "Birthdate should be in the past") + private LocalDate birthDate; + + @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) + @JsonIgnore + private List posts; + + public User() {} + + public User(int id, String name, LocalDate birthDate) { + this.id = id; + this.name = name; + this.birthDate = birthDate; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public LocalDate getBirthDate() { + return birthDate; + } + + public void setBirthDate(LocalDate birthDate) { + this.birthDate = birthDate; + } + + public List getPosts() { + return posts; + } + + public void setPosts(List posts) { + this.posts = posts; + } + + @Override + public String toString() { + return "User{" + "id=" + id + ", name='" + name + '\'' + ", birthDate=" + birthDate + '}'; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/PostRepository.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/PostRepository.java new file mode 100644 index 0000000..6fefcdd --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/PostRepository.java @@ -0,0 +1,7 @@ +package integration.samples.springboot.socialmedia.repository; + +import integration.samples.springboot.socialmedia.model.Post; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PostRepository extends JpaRepository { +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/UserRepository.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/UserRepository.java new file mode 100644 index 0000000..449a84e --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/repository/UserRepository.java @@ -0,0 +1,7 @@ +package integration.samples.springboot.socialmedia.repository; + +import integration.samples.springboot.socialmedia.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Probability.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Probability.java new file mode 100644 index 0000000..feb0475 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Probability.java @@ -0,0 +1,31 @@ +package integration.samples.springboot.socialmedia.sentiment; + +public class Probability { + private double neg; + private double neutral; + private double pos; + + public double getNeg() { + return neg; + } + + public void setNeg(double neg) { + this.neg = neg; + } + + public double getNeutral() { + return neutral; + } + + public void setNeutral(double neutral) { + this.neutral = neutral; + } + + public double getPos() { + return pos; + } + + public void setPos(double pos) { + this.pos = pos; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Sentiment.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Sentiment.java new file mode 100644 index 0000000..71bb114 --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/Sentiment.java @@ -0,0 +1,22 @@ +package integration.samples.springboot.socialmedia.sentiment; + +public class Sentiment { + private Probability probability; + private String label; + + public Probability getProbability() { + return probability; + } + + public void setProbability(Probability probability) { + this.probability = probability; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentProxy.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentProxy.java new file mode 100644 index 0000000..6d56c4d --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentProxy.java @@ -0,0 +1,16 @@ +package integration.samples.springboot.socialmedia.sentiment; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@FeignClient(name="sentiment-api", url="localhost:8088") +public interface SentimentProxy { + @RequestMapping( + method = RequestMethod.POST, + value = "/text-processing/api/sentiment", + consumes = "application/x-www-form-urlencoded" + ) + Sentiment retrieveSentiment(@RequestBody SentimentRequest sentimentRequest); +} diff --git a/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentRequest.java b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentRequest.java new file mode 100644 index 0000000..79b80fb --- /dev/null +++ b/rest-social-media/springboot/src/main/java/integration/samples/springboot/socialmedia/sentiment/SentimentRequest.java @@ -0,0 +1,17 @@ +package integration.samples.springboot.socialmedia.sentiment; + +public class SentimentRequest { + private String text; + + public SentimentRequest(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/rest-social-media/springboot/src/main/resources/application.properties b/rest-social-media/springboot/src/main/resources/application.properties new file mode 100644 index 0000000..95d9cb9 --- /dev/null +++ b/rest-social-media/springboot/src/main/resources/application.properties @@ -0,0 +1,17 @@ +server.port=8087 + +spring.datasource.url=jdbc:mysql://localhost:3306/social_media_database +spring.datasource.username=social_media_user +spring.datasource.password=dummypassword +spring.jpa.hibernate.ddl-auto=update +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect + +logging.pattern.level=trace_id=%mdc{traceId} span_id=%mdc{spanId} trace_flags=%mdc{traceFlags} %p + +spring.jpa.defer-datasource-initialization=true +spring.jpa.show-sql=true + +sentiment.moderate=true + +resilience4j.retry.instances.sentiment-api.maxRetryAttempts=3 +resilience4j.retry.instances.sentiment-api.waitDuration=5s diff --git a/rest-social-media/springboot/src/main/resources/data.sql b/rest-social-media/springboot/src/main/resources/data.sql new file mode 100644 index 0000000..eac075c --- /dev/null +++ b/rest-social-media/springboot/src/main/resources/data.sql @@ -0,0 +1,20 @@ +insert into user_details(id, birth_date, name) +values(1001, current_date(), 'Ranga'); + +insert into user_details(id, birth_date, name) +values(1002, current_date(), 'Ravi'); + +insert into user_details(id, birth_date, name) +values(1003, current_date(), 'Sathish'); + +insert into post(id, description, user_id) +values(2001, 'I want to learn AWS', 1001); + +insert into post(id, description, user_id) +values(2002, 'I want to learn DevOps', 1001); + +insert into post(id, description, user_id) +values(2003, 'I want to learn GCP', 1002); + +insert into post(id, description, user_id) +values(2004, 'I want to learn multi cloud', 1002); diff --git a/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java b/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java new file mode 100644 index 0000000..8961567 --- /dev/null +++ b/rest-social-media/springboot/src/test/java/integration/samples/springboot/socialmedia/SocialMediaApplicationTests.java @@ -0,0 +1,13 @@ +package integration.samples.springboot.socialmedia; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SocialMediaApplicationTests { + + // @Test + // void contextLoads() { + // } + +}