BAEL-1273: add two test of the articles feed controller (#3794)

* BAEL-1216: improve tests

* BAEL-1448: Update Spring 5 articles to use the release version

* Setting up the Maven Wrapper on a maven project

* Add Maven Wrapper on spring-boot module

* simple add

* BAEL-976: Update spring version

* BAEL-1273: Display RSS feed with spring mvc (AbstractRssFeedView)

* Move RSS feed with Spring MVC from spring-boot to spring-mvc-simple

* BAEL-1285: Update Jackson articles

* BAEL-1273: implement both MVC and Rest approach to serve RSS content

* RSS(XML & Json) with a custom model

* BAEL-1273: remove a resource

* BAEL-1519: Guide to scribejava

* BAEL-1273: improve xml representation

* Fix pom

* BAEL-1587: JUnit 5 upgrade

* BAEL-1519: add GitHub implementation and improve article

* BAEL-1273: build a custom message converter to serve Rome Rss feed as json

* BAEL-1273: add two test of the articles feed controller

* Revert "BAEL-1273: add two test of the articles feed controller"

This reverts commit 3e4ced8a16e495971c05bccd5c507c4d68039ea0.

* BAEL-1273: add two test of the articles feed controller

* Remove some others article files
This commit is contained in:
Dassi orleando 2018-03-10 01:48:11 +01:00 committed by maibin
parent 00b3a5148e
commit 42d3de85ba
20 changed files with 219 additions and 641 deletions

24
jsonld/.gitignore vendored
View File

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

Binary file not shown.

View File

@ -1 +0,0 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

View File

@ -1,22 +0,0 @@
JSON-LD
=======
Hypermedia serialization with JSON-LD.
### Requirements
- Maven
- JDK 8
- JSON-LD
### Running
To build and start the server simply type
```bash
$ mvn clean install
$ mvn spring-boot:run
```
Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080)
Enjoy it :)

233
jsonld/mvnw vendored
View File

@ -1,233 +0,0 @@
#!/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
#
# 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# 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 /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
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
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="`which 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
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# 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
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} "$@"

145
jsonld/mvnw.cmd vendored
View File

@ -1,145 +0,0 @@
@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 http://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 Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@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 key stroke 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 enable echoing my 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 "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\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
set MAVEN_CMD_LINE_ARGS=%*
@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="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
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 "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\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%
exit /B %ERROR_CODE%

View File

@ -1,53 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jsonld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>jsonld</name>
<description>Hypermedia serialization with JSON-LD</description>
<parent>
<artifactId>parent-boot-5</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-5</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<jsonld.version>0.11.1</jsonld.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.jsonld-java</groupId>
<artifactId>jsonld-java</artifactId>
<version>${jsonld.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

@ -1,14 +0,0 @@
# the db host
spring.data.mongodb.host=localhost
# the connection port (defaults to 27107)
spring.data.mongodb.port=27017
# The database's name
spring.data.mongodb.database=Jenkins-Pipeline
# Or this
# spring.data.mongodb.uri=mongodb://localhost/Jenkins-Pipeline
# spring.data.mongodb.username=
# spring.data.mongodb.password=
spring.data.mongodb.repositories.enabled=true

View File

@ -1,33 +0,0 @@
package com.baeldung;
import com.github.jsonldjava.core.JsonLdError;
import com.github.jsonldjava.core.JsonLdOptions;
import com.github.jsonldjava.core.JsonLdProcessor;
import com.github.jsonldjava.utils.JsonUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertNotEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class JsonLdSerializatorTest {
@Test
public void whenInserting_andCount_thenWeDontGetZero() throws JsonLdError {
String inputStream = "{name:}";
Object jsonObject = JsonUtils.fromInputStream(inputStream);
Map context = new HashMap();
JsonLdOptions options = new JsonLdOptions();
Object compact = JsonLdProcessor.compact(jsonObject, context, options);
assertNotEquals(0, 0);
}
}

View File

@ -34,6 +34,7 @@
<jackson.version>2.9.4</jackson.version>
<xstream.version>1.4.9</xstream.version>
<scribejava.version>5.1.0</scribejava.version>
<json.version>20180130</json.version>
</properties>
<dependencies>
@ -129,18 +130,6 @@
<artifactId>rome</artifactId>
<version>${rome.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
@ -151,6 +140,11 @@
<artifactId>scribejava-apis</artifactId>
<version>${scribejava.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>

View File

@ -1,17 +1,13 @@
package com.baeldung.spring.configuration;
import com.baeldung.spring.controller.rss.ArticleRssFeedViewResolver;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import com.baeldung.spring.controller.rss.JsonChannelHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.feed.RssChannelHttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@ -28,7 +24,7 @@ import java.util.List;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
class ApplicationConfiguration extends WebMvcConfigurerAdapter {
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
@ -60,16 +56,9 @@ class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
builder.indentOutput(true);
XmlMapper xmlMapper = builder.createXmlMapper(true).build();
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
converters.add(new StringHttpMessageConverter());
converters.add(new RssChannelHttpMessageConverter());
converters.add(new MappingJackson2HttpMessageConverter());
converters.add(new MappingJackson2XmlHttpMessageConverter(xmlMapper));
converters.add(new JsonChannelHttpMessageConverter());
super.configureMessageConverters(converters);
}

View File

@ -1,15 +1,14 @@
package com.baeldung.spring.controller.rss;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class RssData implements Serializable {
public class Article implements Serializable {
private String link;
private String title;
private String description;
private String publishedDate;
private Date publishedDate;
private String author;
public String getLink() {
return link;
@ -35,22 +34,30 @@ public class RssData implements Serializable {
this.description = description;
}
public String getPublishedDate() {
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
this.publishedDate = df.format(publishedDate);
this.publishedDate = publishedDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "RssData{" +
return "Article{" +
"link='" + link + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
", publishedDate=" + publishedDate +
", author='" + author + '\'' +
'}';
}
}

View File

@ -1,29 +0,0 @@
package com.baeldung.spring.controller.rss;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@JacksonXmlRootElement(localName="articles")
public class ArticleFeed extends RssData implements Serializable {
@JacksonXmlProperty(localName = "item")
@JacksonXmlElementWrapper(useWrapping = false)
private List<ArticleItem> items = new ArrayList<ArticleItem>();
public void addItem(ArticleItem articleItem) {
this.items.add(articleItem);
}
public List<ArticleItem> getItems() {
return items;
}
public void setItems(List<ArticleItem> items) {
this.items = items;
}
}

View File

@ -1,22 +0,0 @@
package com.baeldung.spring.controller.rss;
import java.io.Serializable;
public class ArticleItem extends RssData implements Serializable {
private String author;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "ArticleItem{" +
"author='" + author + '\'' +
'}';
}
}

View File

@ -1,10 +1,15 @@
package com.baeldung.spring.controller.rss;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Description;
import com.rometools.rome.feed.rss.Item;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
public class ArticleRssController {
@ -14,33 +19,53 @@ public class ArticleRssController {
return "articleFeedView";
}
@GetMapping(value = "/rss2")
@GetMapping(value = "/rss2", produces = {"application/rss+xml", "application/rss+json"})
@ResponseBody
public ArticleFeed articleRestFeed2() {
ArticleFeed feed = new ArticleFeed();
feed.setLink("http://localhost:8080/spring-mvc-simple/rss");
feed.setTitle("Article Feed");
feed.setDescription("Article Feed Description");
feed.setPublishedDate(new Date());
ArticleItem item1 = new ArticleItem();
public Channel articleHttpFeed() {
List<Article> items = new ArrayList<>();
Article item1 = new Article();
item1.setLink("http://www.baeldung.com/netty-exception-handling");
item1.setTitle("Exceptions in Netty");
item1.setDescription("In this quick article, well be looking at exception handling in Netty.");
item1.setPublishedDate(new Date());
item1.setAuthor("Carlos");
ArticleItem item2 = new ArticleItem();
Article item2 = new Article();
item2.setLink("http://www.baeldung.com/cockroachdb-java");
item2.setTitle("Guide to CockroachDB in Java");
item2.setDescription("This tutorial is an introductory guide to using CockroachDB with Java.");
item2.setPublishedDate(new Date());
item2.setAuthor("Baeldung");
feed.addItem(item1);
feed.addItem(item2);
items.add(item1);
items.add(item2);
Channel channelData = buildChannel(items);
return feed;
return channelData;
}
private Channel buildChannel(List<Article> articles){
Channel channel = new Channel("rss_2.0");
channel.setLink("http://localhost:8080/spring-mvc-simple/rss");
channel.setTitle("Article Feed");
channel.setDescription("Article Feed Description");
channel.setPubDate(new Date());
List<Item> items = new ArrayList<>();
for (Article article : articles) {
Item item = new Item();
item.setLink(article.getLink());
item.setTitle(article.getTitle());
Description description1 = new Description();
description1.setValue(article.getDescription());
item.setDescription(description1);
item.setPubDate(article.getPublishedDate());
item.setAuthor(article.getAuthor());
items.add(item);
}
channel.setItems(items);
return channel;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.spring.controller.rss;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.WireFeedOutput;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
public class JsonChannelHttpMessageConverter extends AbstractHttpMessageConverter<Channel> {
public JsonChannelHttpMessageConverter(){
super(new MediaType("application", "rss+json"));
}
@Override
protected boolean supports(Class<?> aClass) {
return Channel.class.isAssignableFrom(aClass);
}
@Override
protected Channel readInternal(Class<? extends Channel> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
protected void writeInternal(Channel wireFeed, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
WireFeedOutput feedOutput = new WireFeedOutput();
try {
String xmlStr = feedOutput.outputString(wireFeed, true);
JSONObject xmlJSONObj = XML.toJSONObject(xmlStr);
String jsonPrettyPrintString = xmlJSONObj.toString(4);
outputMessage.getBody().write(jsonPrettyPrintString.getBytes());
} catch (JSONException | FeedException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.spring.controller.scribe;
import com.github.scribejava.apis.GitHubApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.*;
import com.github.scribejava.core.oauth.OAuth20Service;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutionException;
@Controller
@RequestMapping("github")
public class GithubController {
private OAuth20Service createService(String state) {
return new ServiceBuilder("e1f8d4f1a5c71467a159")
.apiSecret("4851597541a8f33a4f1bf1c70f3cedcfefbeb13b")
.state(state)
.callback("http://localhost:8080/spring-mvc-simple/github/callback")
.build(GitHubApi.instance());
}
@GetMapping(value = "/authorization")
public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException {
String state = String.valueOf(new Random().nextInt(999_999));
OAuth20Service githubService = createService(state);
servletReq.getSession().setAttribute("state", state);
String authorizationUrl = githubService.getAuthorizationUrl();
RedirectView redirectView = new RedirectView();
redirectView.setUrl(authorizationUrl);
return redirectView;
}
@GetMapping(value = "/callback", produces = "text/plain")
@ResponseBody
public String callback(HttpServletRequest servletReq, @RequestParam("code") String code, @RequestParam("state") String state) throws InterruptedException, ExecutionException, IOException {
String initialState = (String) servletReq.getSession().getAttribute("state");
if(initialState.equals(state)) {
OAuth20Service githubService = createService(initialState);
OAuth2AccessToken accessToken = githubService.getAccessToken(code);
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.github.com/user");
githubService.signRequest(accessToken, request);
Response response = githubService.execute(request);
return response.getBody();
}
return "Error";
}
}

View File

@ -17,18 +17,18 @@ import java.util.concurrent.ExecutionException;
@Controller
@RequestMapping("twitter")
public class ScribeController {
public class TwitterController {
private OAuth10aService createTwitterService() {
private OAuth10aService createService() {
return new ServiceBuilder("PSRszoHhRDVhyo2RIkThEbWko")
.apiSecret("prpJbz03DcGRN46sb4ucdSYtVxG8unUKhcnu3an5ItXbEOuenL")
.callback("http://localhost:8080/spring-mvc-simple/twitter/callback")
.build(TwitterApi.instance());
.apiSecret("prpJbz03DcGRN46sb4ucdSYtVxG8unUKhcnu3an5ItXbEOuenL")
.callback("http://localhost:8080/spring-mvc-simple/twitter/callback")
.build(TwitterApi.instance());
}
@GetMapping(value = "/authorization")
public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException {
OAuth10aService twitterService = createTwitterService();
OAuth10aService twitterService = createService();
OAuth1RequestToken requestToken = twitterService.getRequestToken();
String authorizationUrl = twitterService.getAuthorizationUrl(requestToken);
@ -42,7 +42,7 @@ public class ScribeController {
@GetMapping(value = "/callback", produces = "text/plain")
@ResponseBody
public String callback(HttpServletRequest servletReq, @RequestParam("oauth_verifier") String oauthV) throws InterruptedException, ExecutionException, IOException {
OAuth10aService twitterService = createTwitterService();
OAuth10aService twitterService = createService();
OAuth1RequestToken requestToken = (OAuth1RequestToken) servletReq.getSession().getAttribute("requestToken");
OAuth1AccessToken accessToken = twitterService.getAccessToken(requestToken, oauthV);

View File

@ -0,0 +1,45 @@
package com.baeldung.controller.rss;
import com.baeldung.spring.configuration.ApplicationConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringJUnitWebConfig(ApplicationConfiguration.class)
public class ArticleRssIntegrationTest {
public static final String APPLICATION_RSS_XML = "application/rss+xml";
public static final String APPLICATION_RSS_JSON = "application/rss+json";
public static final String APPLICATION_RSS_XML_CHARSET_UTF_8 = "application/rss+xml;charset=UTF-8";
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext)
.build();
}
@Test
public void whenRequestingXMLFeed_thenContentTypeIsOk() throws Exception {
mockMvc.perform(get("/rss2").accept(APPLICATION_RSS_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_RSS_XML_CHARSET_UTF_8));
}
@Test
public void whenRequestingJSONFeed_thenContentTypeIsOk() throws Exception {
mockMvc.perform(get("/rss2").accept(APPLICATION_RSS_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_RSS_JSON));
}
}