I'm trying to create a proof of concept Spring Boot application that leverages Thymeleaf to populate a string structure based upon properties and request parameters. I had it working using the Model implementation, but that only works if the populated template is the response. In this case, I want the populated template to be used within the project.
#Controller
#RequestMapping("/poc")
public class InfoController {
#Autowired
ThymeleafService thymeleafService;
#Value("${reportType}")
private String reportType;
// This function works - the reportType variable is populated based upon application.properties
#GetMapping("/map")
public String testMap(#RequestParam(name = "id", required = false, defaultValue = "2")
String id, Model model){
model.addAttribute("reportType", "\"" + reportType + "\"");
return id + ".json";
}
// this function does not work - the reportType variable is null
#RequestMapping(value = "/map2",method= RequestMethod.POST)
public String testMap2(#RequestBody MapRequest request, #RequestParam(name = "id", required = false, defaultValue = "2")
String id, Model model) {
String output = thymeleafService.processTemplate(request, id);
return output;
}
}
The ThymeleafService is pretty simple.
#Component
public class ThymeleafService {
#Value("${reportType}")
private String reportType;
private TemplateEngine templateEngine;
public String processTemplate(MapRequest request, String templateId){
templateEngine = new TemplateEngine();
StringTemplateResolver resolver = new StringTemplateResolver();
resolver.setTemplateMode(TemplateMode.TEXT);
templateEngine.addTemplateResolver(resolver);
// Map<String, Object> attributes = new HashMap<>();
final Context ctxt = new Context(Locale.US);
ctxt.setVariable("reportType", "\"" + reportType + "\"");
// for (String name : ctxt.getVariableNames()){
//// attributes.put(name, ctxt.getVariable(name));
// }
TemplateSpec templateSpec = new TemplateSpec(templateId + ".json", null, TemplateMode.TEXT, attributes);
StringWriter writer = new StringWriter();
templateEngine.process(templateSpec, ctxt, writer);
return writer.toString();
}
}
POM.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.poc</groupId>
<artifactId>map</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mappoc</name>
<description>POC</description>
<properties>
<java.version>11</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Here is the template:
ReportType: [(${reportType})]
What I end up getting back from map is:
ReportType: "configReportType"
But what I end up getting back from map2 is:
ReportType:
I've tried setting the attributes in the Context, with and without an AttributeMap in the TemplateEngine.process function. I've tried using a TemplateSpec and tried just a string for the template name.
I've debugged the code and confirmed that the reportType variable is getting set and passed into the process function. But for some reason beyond me, it's not actually injecting the data into the response. I feel like I'm missing something really obvious, but I can't figure it. Any help would be greatly appreciated.
NOTE: The reason I can't just use the Model paradigm is because while right now, it returns the data to the caller, the end goal is to USE that data.
I finally managed to get this working - the trick was that I had to:
Use ClassLoaderTemplateResolver instead of StringTemplateResolver
Change the response in the Controller from String to ResponseEntity
Remove Model from the Controller signature
i think the syntax of your variable is incorect
It should be [[${reportType}]] not [(${reportType})]
This is how I make use of it with thymeleaf 3.0
Related
I am trying to return an image as shown here https://www.baeldung.com/spring-mvc-image-media-data
All methods that are shown there are working properly, except for the last one.
#ResponseBody
#RequestMapping(value = "/image-resource", method = RequestMethod.GET)
public Resource getImageAsResource() {
return new ServletContextResource(servletContext, "/WEB-INF/images/image-example.jpg");
}
or, if we want more control over the response headers:
#RequestMapping(value = "/image-resource", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Resource> getImageAsResource() {
HttpHeaders headers = new HttpHeaders();
Resource resource =
new ServletContextResource(servletContext, "/WEB-INF/images/image-example.jpg");
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
When using this method, I get an error: The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.
I tried many options and none of them helped. I studied these pages
HTTP Status 406 – Not Acceptable in spring MVC
"Could not find acceptable representation" using spring-boot-starter-web
Could not find acceptable representation
and many others and none of the answers on these pages helped solve the problem.
If I do:
#GetMapping(value = "/image4", produces = "image/jpeg")
then I get the error: No converter for [class org.springframework.web.context.support.ServletContextResource] with preset Content-Type 'null'
If I do:
#GetMapping(value = "/image4", consumes = "image/jpeg")
then I get the error: The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.
This is my github project https://github.com/MyTestPerson/images
Please tell me what am I doing wrong?
Image.class
#Controller
public class Image {
#Autowired
ServletContext servletContext;
#ResponseBody()
#GetMapping(value = "/image4")
public Resource getImage4() {
return new ServletContextResource(servletContext, "/WEB-INF/image/jackson.jpg");
}
#ResponseBody
#GetMapping(value = "/image5")
public ResponseEntity<Resource> getImage5() {
HttpHeaders headers = new HttpHeaders();
Resource resource = new ServletContextResource(servletContext, "/WEB-INF/image/jackson.jpg");
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}
RootConfig.class
#EnableWebMvc
#Configuration
public class RootConfig implements WebMvcConfigurer {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
}
#Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
}
POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.images</groupId>
<artifactId>images</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${encoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
<java.version>11</java.version>
<encoding>UTF-8</encoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>5.3.9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-bom</artifactId>
<version>5.5.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.7.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Framework-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- Freemarker-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<!-- Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- Apache Commons IO-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- com fasterxml jackson data format-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.12.4</version>
</dependency>
<!-- Testing-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.19.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
<!-- Logging-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
</dependency>
</dependencies>
</project>
Thanks to #Andreas
RootConfig.class
#EnableWebMvc
#Configuration
public class RootConfig implements WebMvcConfigurer {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
converters.add(resourceHttpMessageConverter());
}
#Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
#Bean
public ResourceHttpMessageConverter resourceHttpMessageConverter(){
ResourceHttpMessageConverter resourceHttpMessageConverter = new ResourceHttpMessageConverter();
resourceHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return resourceHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
}
When i run the STS(SpringBoot) application i get the below error:
The attempt was made from the following location: org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1321)
The following method did not exist:
javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;
The method's class, javax.servlet.ServletContext, is available from the following locations:
jar:file:/home/talha/.m2/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar!/javax/servlet/ServletContext.class
jar:file:/home/talha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.33/tomcat-embed-core-9.0.33.jar!/javax/servlet/ServletContext.class
It was loaded from the following location:
file:/home/talha/.m2/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar
The suggestion in the ide is:
Action:
Correct the classpath of your application so that it contains a single, compatible version of javax.servlet.ServletContext
I guess there is something wrong with my pom.xml the code is as below:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.uni</groupId>
<artifactId>authorize</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>authorize</name>
<description>API for user registration and login with validation</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.jsontoken</groupId>
<artifactId>jsontoken</artifactId>
<version>1.0</version>
</dependency>
<!-- Thanks for using https://jar-download.com -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>authrize</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The main dependencies causing the error are:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.jsontoken</groupId>
<artifactId>jsontoken</artifactId>
<version>1.0</version>
</dependency>
I get the error only after adding the above dependencies, the need to add the dependencies is the below class:
package com.uni.authorize.service;
import java.security.InvalidKeyException;
import java.security.SignatureException;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import com.google.gson.JsonObject;
import com.uni.authorize.model.TokenKeys;
import com.uni.authorize.pojo.TokenObject;
import com.uni.authorize.repository.TokenKeysRepository;
import com.uni.authorize.service.CreateToken;
import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.crypto.HmacSHA256Signer;
#Configuration
public class CreateToken {
private static final Logger LOGGER = LoggerFactory.getLogger(CreateToken.class);
private static final String ISSUER = "UnI United Tech";
#Autowired
TokenKeysRepository tokenKeyRepository;
public TokenObject createToken(String userId) {
List<TokenKeys> tokenList = tokenKeyRepository.findAll();
TokenKeys tokenKeys = tokenList.get(0);
long accessTokenValidity = tokenKeys.getAccessTokenValidity();
long refreshTokenValidiry = tokenKeys.getRefreshTokenValidity();
String accessTokenKey = tokenKeys.getAccessKey();
String refreshTokenKey = tokenKeys.getRefreshKey();
String accessToken = generateAccessToken(userId, accessTokenKey, accessTokenValidity);
String refreshToken = generateRefreshToken(userId, refreshTokenKey, refreshTokenValidiry);
TokenObject tokenObject = new TokenObject();
tokenObject.setAccess_token(accessToken);
tokenObject.setRefresh_token(refreshToken);
tokenObject.setToken_type("bearer");
tokenObject.setExpires_in(accessTokenValidity);
tokenObject.setScope("read write trust");
return tokenObject;
}
private String generateAccessToken(String userId, String accessTokenKey, long accessTokenValidity) {
HmacSHA256Signer signer;
try {
signer = new HmacSHA256Signer(ISSUER, null, accessTokenKey.getBytes());
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
// Configure JSON token
JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
// token.setAudience(AUDIENCE);
DateTime dateTime = new DateTime();
long dateTimeMillis = dateTime.getMillis();
// DateTime currentTimeDateTime = new DateTime(dateTimeMillis);
// DateTime expiryTimeDateTime = new DateTime(dateTimeMillis + accessTokenValidity);
Instant currentTimeInstant = new org.joda.time.Instant(dateTimeMillis);
Instant expirationTimeInstant = new org.joda.time.Instant(dateTimeMillis + accessTokenValidity);
LOGGER.debug("Current Time Instant" + currentTimeInstant);
LOGGER.debug("Expiration Tine Instant" + expirationTimeInstant);
token.setIssuedAt(currentTimeInstant);
token.setExpiration(expirationTimeInstant);
// Configure request object, which provides information of the item
JsonObject request = new JsonObject();
request.addProperty("userId", userId);
JsonObject payload = token.getPayloadAsJsonObject();
payload.add("info", request);
try {
return token.serializeAndSign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
private String generateRefreshToken(String userId, String refreshTokenKey, long refreshTokenValidiry) {
HmacSHA256Signer signer;
try {
signer = new HmacSHA256Signer(ISSUER, null, refreshTokenKey.getBytes());
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
// Configure JSON token
JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
// token.setAudience(AUDIENCE);
DateTime dateTime = new DateTime();
long dateTimeMillis = dateTime.getMillis();
// DateTime currentTimeDateTime = new DateTime(dateTimeMillis);
// DateTime expiryTimeDateTime = new DateTime(dateTimeMillis + refreshTokenValidiry);
Instant currentTimeInstant = new org.joda.time.Instant(dateTimeMillis);
Instant expirationTimeInstant = new org.joda.time.Instant(dateTimeMillis + refreshTokenValidiry);
LOGGER.debug("Current Time Instant" + currentTimeInstant);
LOGGER.debug("Expiration Tine Instant" + expirationTimeInstant);
token.setIssuedAt(currentTimeInstant);
token.setExpiration(expirationTimeInstant);
// Configure request object, which provides information of the item
JsonObject request = new JsonObject();
request.addProperty("userId", userId);
JsonObject payload = token.getPayloadAsJsonObject();
payload.add("info", request);
try {
return token.serializeAndSign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
}
Please help me resolve this issue.
Thanks in advance
getVirtualServerName() was added in Servlet 3.1, but you included servlet-api-2.5.jar is your application.
Options:
Change your dependencies to include servlet-api-3.1.jar (or later)
Remove the servlet-api-2.5.jar dependency, since the correct version is included in the Embedded Tomcat file (tomcat-embed-core-9.0.33.jar).
Actually, you should never ship servlet-api.jar with your application, since it will be provided by the Servlet Container. Seems you're missing <scope>provided</scope> in your dependency tag for the servlet-api file.
I solved a similar issue by adding dependencyManagement.
Here is an example of my code where a version of org.springframework.cloud was the problem:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
I'm trying to make a Spring Boot Application with simple login page but when i try to use #Autowired with a interface that i created seems to be a problem. I read 7-8 similar questions but the answers that i find there was useless for me. #Autowired works fine when i use it on interface that expends JpaRepository.
my structure is:
My packages are on the same level as my Application file .
Here is my controller
#Controller
#RequestMapping(value = "/users")
public class LoginContoller {
#Autowired
UsersRepositoryCustom usersRepositoryCustom;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginForm(){
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public #ResponseBody
String verifyLogin(#RequestParam String name, #RequestParam String password) {
System.out.println("Controller: name: " + name + " pass " + password);
Users users=usersRepositoryCustom.loginUser(name, password);
if (users==null) {
System.out.println("login control user null");
return "login";
}
return "users/all";
}
}
Repository:
#Repository
public interface UsersRepositoryCustom {
Users loginUser(String name, String password);
}
I do not think it helps but here is the implementation
public abstract class UserImpl implements UsersRepositoryCustom {
#Autowired
UsersRepository usersRepository;
#Override
public Users loginUser(String name, String password) {
System.out.println("UserImpl: nume: " + name + " pass " + password);
Users user=usersRepository.findByUsername(name);
if (user != null && user.getPassword().equals(password)) {
System.out.println("User Login"+user.getId()+" "+user.getUsername());
return user;
}
return null;
}
}
Application.properties:
server.port=8080
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3308/assignment-one-db
spring.datasource.username=root
spring.datasource.password=789456123
spring.jpa.hibernate.ddl-auto= update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.asg1</groupId>
<artifactId>asg1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>asg1</name>
<description>assignment1</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I try to use #EnableJpaRepositories, #EnableAutoConfiguration but it was useless
Here is the error:
Description:
Field usersRepositoryCustom in com.asg1.asg1.controllers.LoginContoller required a bean of type 'com.asg1.asg1.repository.UsersRepositoryCustom' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.asg1.asg1.repository.UsersRepositoryCustom' in your configuration.
Process finished with exit code 1
I am able to return a JSONP from a custom java object without problems (following this: http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity), but when i try to return a String withing the JSONP the wrapping function disappears
What i am doing:
#RequestMapping(value ="/book", produces = {MediaType.APPLICATION_JSON_VALUE, "application/javascript"})
public #ResponseBody ResponseEntity<String> bookInfo() {
JSONObject test = new JSONObject();
test.put("uno", "uno");
return new ResponseEntity<String>(test.toString(), HttpStatus.OK);
}
Call to the service:
http://<server>:port//book?callback=test
Returns:
{"uno":"uno"}
Expected result:
test({"uno":"uno"})
Also tried to return directly the JSONObject ResponseEntity.accepted().body(test); but i got a 406 Error. Any ideas?
The error looks like the class JsonpAdvice from this example, isn't available for the request mapping.
#ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("callback");
}
}
I used HashMap, since it has a similar use here and HashMap is more straightforward to use in this example:
#RequestMapping(value="/book", produces=MediaType.APPLICATION_JSON)
public ResponseEntity<Map> bookInfo() {
Map test = new HashMap();
test.put("uno", "uno");
return ResponseEntity.accepted().body(test);
}
This provided me with the result:
// http://localhost:8080/book?callback=test
/**/test({
"uno": "uno"
});
I was using Spring boot:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
I have already asked this question for Spring XD. I am now trying to migrate to Spring CDF.
I found this link and I tried to reuse the code there and change the encoding with mine.
I created the following POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>tcp-ber-source</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>TCP Ber Source</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<tcp-app-starters-common.version>1.1.0.RELEASE</tcp-app-starters-common.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud.stream.app</groupId>
<artifactId>tcp-app-starters-common</artifactId>
<version>${tcp-app-starters-common.version}</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>ber-byte-array-serializers</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Configuration:
#EnableBinding(Source.class)
#EnableConfigurationProperties(TcpBerSourceProperties.class)
public class TcpBerSourceConfiguration {
private final Source channels;
private final TcpBerSourceProperties properties;
#Autowired
public TcpSourceConfiguration(final TcpBerSourceProperties properties, final Source channels) {
this.properties = properties;
this.channels = channels;
}
#Bean
public TcpReceivingChannelAdapter adapter(#Qualifier("tcpBerSourceConnectionFactory") final AbstractConnectionFactory connectionFactory) {
final TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
adapter.setConnectionFactory(connectionFactory);
adapter.setOutputChannel(this.channels.output());
return adapter;
}
#Bean
public TcpConnectionFactoryFactoryBean tcpBerSourceConnectionFactory(#Qualifier("tcpBerSourceDecoder") final AbstractByteArraySerializer decoder) throws Exception {
final TcpConnectionFactoryFactoryBean factoryBean = new TcpConnectionFactoryFactoryBean();
factoryBean.setType("server");
factoryBean.setPort(this.properties.getPort());
factoryBean.setUsingNio(this.properties.isNio());
factoryBean.setUsingDirectBuffers(this.properties.isUseDirectBuffers());
factoryBean.setLookupHost(this.properties.isReverseLookup());
factoryBean.setDeserializer(decoder);
factoryBean.setSoTimeout(this.properties.getSocketTimeout());
return factoryBean;
}
#Bean
public BerEncoderDecoderFactoryBean tcpBerSourceDecoder() {
final BerEncoderDecoderFactoryBean factoryBean = new BerEncoderDecoderFactoryBean(this.properties.getDecoder());
factoryBean.setMaxMessageSize(this.properties.getBufferSize());
return factoryBean;
}
}
And this FactoryBean:
public class BerEncoderDecoderFactoryBean extends AbstractFactoryBean<AbstractByteArraySerializer> implements ApplicationEventPublisherAware {
private final BerEncoding encoding;
private ApplicationEventPublisher applicationEventPublisher;
private Integer maxMessageSize;
public BerEncoderDecoderFactoryBean(final BerEncoding encoding) {
Assert.notNull(encoding, "'encoding' cannot be null");
this.encoding = encoding;
}
#Override
public void setApplicationEventPublisher(final ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
/**
* The maximum message size allowed when decoding.
* #param maxMessageSize the maximum message size.
*/
public void setMaxMessageSize(final int maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
#Override
protected AbstractByteArraySerializer createInstance() throws Exception {
final AbstractByteArraySerializer codec;
switch (this.encoding) {
case SPLIT:
codec = new ByteArrayBerSplitSerializer();
break;
case EXTRACT:
codec = new ByteArrayBerExtractSerializer();
break;
default:
throw new IllegalArgumentException("Invalid encoding: " + this.encoding);
}
codec.setApplicationEventPublisher(this.applicationEventPublisher);
if (this.maxMessageSize != null) {
codec.setMaxMessageSize(this.maxMessageSize);
}
return codec;
}
#Override
public Class<?> getObjectType() {
return AbstractByteArraySerializer.class;
}
}
BerEncoding is a simple enum, and TcpBerSourceProperties are pretty straightforward.
Is this the right approach?
If it is, how can I run this? I can't see #SpringBootApplication anywhere on the tcp stream app starters I found on the mentioned link to run as Spring Boot standalone applications?
You have to create your own Spring Boot App class and import the configuration class; see the documentation about creating custom apps.
We generate a standard app (for rabbit and kafka binders) from the starters as explained here.