repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java | spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/ApiClient.java | package com.baeldung.petstore.client.invoker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.RequestEntity.BodyBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import com.baeldung.petstore.client.invoker.auth.Authentication;
import com.baeldung.petstore.client.invoker.auth.HttpBasicAuth;
import com.baeldung.petstore.client.invoker.auth.ApiKeyAuth;
import com.baeldung.petstore.client.invoker.auth.OAuth;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00")
@Component("com.baeldung.petstore.client.invoker.ApiClient")
public class ApiClient {
public enum CollectionFormat {
CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null);
private final String separator;
private CollectionFormat(String separator) {
this.separator = separator;
}
private String collectionToString(Collection<? extends CharSequence> collection) {
return StringUtils.collectionToDelimitedString(collection, separator);
}
}
private boolean debugging = false;
private HttpHeaders defaultHeaders = new HttpHeaders();
private String basePath = "http://petstore.swagger.io/v2";
private RestTemplate restTemplate;
private Map<String, Authentication> authentications;
private HttpStatus statusCode;
private MultiValueMap<String, String> responseHeaders;
private DateFormat dateFormat;
public ApiClient() {
this.restTemplate = buildRestTemplate();
init();
}
@Autowired
public ApiClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
init();
}
protected void init() {
// Use RFC3339 format for date and datetime.
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
this.dateFormat = new RFC3339DateFormat();
// Use UTC as the default time zone.
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent.
setUserAgent("Java-SDK");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
authentications.put("petstore_auth", new OAuth());
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
/**
* Get the current base path
* @return String the base path
*/
public String getBasePath() {
return basePath;
}
/**
* Set the base path, which should include the host
* @param basePath the base path
* @return ApiClient this client
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Gets the status code of the previous request
* @return HttpStatus the status code
*/
public HttpStatus getStatusCode() {
return statusCode;
}
/**
* Gets the response headers of the previous request
* @return MultiValueMap a map of response headers
*/
public MultiValueMap<String, String> getResponseHeaders() {
return responseHeaders;
}
/**
* Get authentications (key: authentication name, value: authentication).
* @return Map the currently configured authentication types
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set username for the first HTTP basic authentication.
* @param username the username
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
* @param password the password
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
* @param apiKey the API key
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
* @param apiKeyPrefix the API key prefix
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set access token for the first OAuth2 authentication.
* @param accessToken the access token
*/
public void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).setAccessToken(accessToken);
return;
}
}
throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
* @param userAgent the user agent string
* @return ApiClient this client
*/
public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent);
return this;
}
/**
* Add a default header.
*
* @param name The header's name
* @param value The header's value
* @return ApiClient this client
*/
public ApiClient addDefaultHeader(String name, String value) {
defaultHeaders.add(name, value);
return this;
}
public void setDebugging(boolean debugging) {
List<ClientHttpRequestInterceptor> currentInterceptors = this.restTemplate.getInterceptors();
if(debugging) {
if (currentInterceptors == null) {
currentInterceptors = new ArrayList<ClientHttpRequestInterceptor>();
}
ClientHttpRequestInterceptor interceptor = new ApiClientHttpRequestInterceptor();
currentInterceptors.add(interceptor);
this.restTemplate.setInterceptors(currentInterceptors);
} else {
if (currentInterceptors != null && !currentInterceptors.isEmpty()) {
Iterator<ClientHttpRequestInterceptor> iter = currentInterceptors.iterator();
while (iter.hasNext()) {
ClientHttpRequestInterceptor interceptor = iter.next();
if (interceptor instanceof ApiClientHttpRequestInterceptor) {
iter.remove();
}
}
this.restTemplate.setInterceptors(currentInterceptors);
}
}
this.debugging = debugging;
}
/**
* Check that whether debugging is enabled for this API client.
* @return boolean true if this client is enabled for debugging, false otherwise
*/
public boolean isDebugging() {
return debugging;
}
/**
* Get the date format used to parse/format date parameters.
* @return DateFormat format
*/
public DateFormat getDateFormat() {
return dateFormat;
}
/**
* Set the date format used to parse/format date parameters.
* @param dateFormat Date format
* @return API client
*/
public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
return this;
}
/**
* Parse the given string into Date object.
*/
public Date parseDate(String str) {
try {
return dateFormat.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Format the given Date object into string.
*/
public String formatDate(Date date) {
return dateFormat.format(date);
}
/**
* Format the given parameter object into string.
* @param param the object to convert
* @return String the parameter represented as a String
*/
public String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDate( (Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>) param) {
if(b.length() > 0) {
b.append(",");
}
b.append(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/**
* Converts a parameter to a {@link MultiValueMap} for use in REST requests
* @param collectionFormat The format to convert to
* @param name The name of the parameter
* @param value The parameter's value
* @return a Map containing the String value(s) of the input parameter
*/
public MultiValueMap<String, String> parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) {
final MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
if (name == null || name.isEmpty() || value == null) {
return params;
}
if(collectionFormat == null) {
collectionFormat = CollectionFormat.CSV;
}
Collection<?> valueCollection = null;
if (value instanceof Collection) {
valueCollection = (Collection<?>) value;
} else {
params.add(name, parameterToString(value));
return params;
}
if (valueCollection.isEmpty()){
return params;
}
if (collectionFormat.equals(CollectionFormat.MULTI)) {
for (Object item : valueCollection) {
params.add(name, parameterToString(item));
}
return params;
}
List<String> values = new ArrayList<String>();
for(Object o : valueCollection) {
values.add(parameterToString(o));
}
params.add(name, collectionFormat.collectionToString(values));
return params;
}
/**
* Check if the given {@code String} is a JSON MIME.
* @param mediaType the input MediaType
* @return boolean true if the MediaType represents JSON, false otherwise
*/
public boolean isJsonMime(String mediaType) {
try {
return isJsonMime(MediaType.parseMediaType(mediaType));
} catch (InvalidMediaTypeException e) {
}
return false;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* @param mediaType the input MediaType
* @return boolean true if the MediaType represents JSON, false otherwise
*/
public boolean isJsonMime(MediaType mediaType) {
return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$"));
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return List The list of MediaTypes to use for the Accept header
*/
public List<MediaType> selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
MediaType mediaType = MediaType.parseMediaType(accept);
if (isJsonMime(mediaType)) {
return Collections.singletonList(mediaType);
}
}
return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts));
}
/**
* Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it;
* otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return MediaType The Content-Type header to use. If the given array is empty, JSON will be used.
*/
public MediaType selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) {
return MediaType.APPLICATION_JSON;
}
for (String contentType : contentTypes) {
MediaType mediaType = MediaType.parseMediaType(contentType);
if (isJsonMime(mediaType)) {
return mediaType;
}
}
return MediaType.parseMediaType(contentTypes[0]);
}
/**
* Select the body to use for the request
* @param obj the body object
* @param formParams the form parameters
* @param contentType the content type of the request
* @return Object the selected body
*/
protected Object selectBody(Object obj, MultiValueMap<String, Object> formParams, MediaType contentType) {
boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType);
return isForm ? formParams : obj;
}
/**
* Invoke API by sending HTTP request with the given options.
*
* @param <T> the return type to use
* @param path The sub-path of the HTTP URL
* @param method The request method
* @param queryParams The query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @param returnType The return type into which to deserialize the response
* @return The response body in chosen type
*/
public <T> T invokeAPI(String path, HttpMethod method, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
updateParamsForAuth(authNames, queryParams, headerParams);
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path);
if (queryParams != null) {
builder.queryParams(queryParams);
}
final BodyBuilder requestBuilder = RequestEntity.method(method, builder.build().toUri());
if(accept != null) {
requestBuilder.accept(accept.toArray(new MediaType[accept.size()]));
}
if(contentType != null) {
requestBuilder.contentType(contentType);
}
addHeadersToRequest(headerParams, requestBuilder);
addHeadersToRequest(defaultHeaders, requestBuilder);
RequestEntity<Object> requestEntity = requestBuilder.body(selectBody(body, formParams, contentType));
ResponseEntity<T> responseEntity = restTemplate.exchange(requestEntity, returnType);
statusCode = responseEntity.getStatusCode();
responseHeaders = responseEntity.getHeaders();
if (responseEntity.getStatusCode() == HttpStatus.NO_CONTENT) {
return null;
} else if (responseEntity.getStatusCode().is2xxSuccessful()) {
if (returnType == null) {
return null;
}
return responseEntity.getBody();
} else {
// The error handler built into the RestTemplate should handle 400 and 500 series errors.
throw new RestClientException("API returned " + statusCode + " and it wasn't handled by the RestTemplate error handler");
}
}
/**
* Add headers to the request that is being built
* @param headers The headers to add
* @param requestBuilder The current request
*/
protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) {
for (Entry<String, List<String>> entry : headers.entrySet()) {
List<String> values = entry.getValue();
for(String value : values) {
if (value != null) {
requestBuilder.header(entry.getKey(), value);
}
}
}
}
/**
* Build the RestTemplate used to make HTTP requests.
* @return RestTemplate
*/
protected RestTemplate buildRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
// This allows us to read the response more than once - Necessary for debugging.
restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
return restTemplate;
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
* @param queryParams The query parameters
* @param headerParams The header parameters
*/
private void updateParamsForAuth(String[] authNames, MultiValueMap<String, String> queryParams, HttpHeaders headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) {
throw new RestClientException("Authentication undefined: " + authName);
}
auth.applyToParams(queryParams, headerParams);
}
}
private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
logRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
logResponse(response);
return response;
}
private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException {
log.info("URI: " + request.getURI());
log.info("HTTP Method: " + request.getMethod());
log.info("HTTP Headers: " + headersToString(request.getHeaders()));
log.info("Request Body: " + new String(body, StandardCharsets.UTF_8));
}
private void logResponse(ClientHttpResponse response) throws IOException {
log.info("HTTP Status Code: " + response.getRawStatusCode());
log.info("Status Text: " + response.getStatusText());
log.info("HTTP Headers: " + headersToString(response.getHeaders()));
log.info("Response Body: " + bodyToString(response.getBody()));
}
private String headersToString(HttpHeaders headers) {
StringBuilder builder = new StringBuilder();
for(Entry<String, List<String>> entry : headers.entrySet()) {
builder.append(entry.getKey()).append("=[");
for(String value : entry.getValue()) {
builder.append(value).append(",");
}
builder.setLength(builder.length() - 1); // Get rid of trailing comma
builder.append("],");
}
builder.setLength(builder.length() - 1); // Get rid of trailing comma
return builder.toString();
}
private String bodyToString(InputStream body) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8));
String line = bufferedReader.readLine();
while (line != null) {
builder.append(line).append(System.lineSeparator());
line = bufferedReader.readLine();
}
bufferedReader.close();
return builder.toString();
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java | spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/ApiKeyAuth.java | package com.baeldung.petstore.client.invoker.auth;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00")
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams) {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if (location.equals("query")) {
queryParams.add(paramName, value);
} else if (location.equals("header")) {
headerParams.add(paramName, value);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java | spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuth.java | package com.baeldung.petstore.client.invoker.auth;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00")
public class OAuth implements Authentication {
private String accessToken;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams) {
if (accessToken != null) {
headerParams.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java | spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/Authentication.java | package com.baeldung.petstore.client.invoker.auth;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
public interface Authentication {
/**
* Apply authentication settings to header and / or query parameters.
* @param queryParams The query parameters for the request
* @param headerParams The header parameters for the request
*/
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java | spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/OAuthFlow.java | package com.baeldung.petstore.client.invoker.auth;
public enum OAuthFlow {
accessCode, implicit, password, application
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java | spring-swagger-codegen-modules/spring-swagger-codegen-api-client/src/main/java/com/baeldung/petstore/client/invoker/auth/HttpBasicAuth.java | package com.baeldung.petstore.client.invoker.auth;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-29T12:04:37.072+02:00")
public class HttpBasicAuth implements Authentication {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams) {
if (username == null && password == null) {
return;
}
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder()
.encodeToString(str.getBytes(StandardCharsets.UTF_8)));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceIntegrationTest.java | spring-core-3/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceIntegrationTest.java | package com.baeldung.beanfactory;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BeanFactoryWithClassPathResourceIntegrationTest {
@Test
public void createBeanFactoryAndCheckEmployeeBean() {
Resource res = new ClassPathResource("beanfactory-example.xml");
BeanFactory factory = new XmlBeanFactory(res);
Employee emp = (Employee) factory.getBean("employee");
assertTrue(factory.isSingleton("employee"));
assertTrue(factory.getBean("employee") instanceof Employee);
assertTrue(factory.isTypeMatch("employee", Employee.class));
assertTrue(factory.getAliases("employee").length > 0);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanIntegrationTest.java | spring-core-3/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanIntegrationTest.java | package com.baeldung.factorybean;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:factorybean-abstract-spring-ctx.xml" })
public class AbstractFactoryBeanIntegrationTest {
@Resource(name = "singleTool")
private Tool tool1;
@Resource(name = "singleTool")
private Tool tool2;
@Resource(name = "nonSingleTool")
private Tool tool3;
@Resource(name = "nonSingleTool")
private Tool tool4;
@Test
public void testSingleToolFactory() {
assertThat(tool1.getId(), equalTo(1));
assertTrue(tool1 == tool2);
}
@Test
public void testNonSingleToolFactory() {
assertThat(tool3.getId(), equalTo(2));
assertThat(tool4.getId(), equalTo(2));
assertTrue(tool3 != tool4);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigIntegrationTest.java | spring-core-3/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigIntegrationTest.java | package com.baeldung.factorybean;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:factorybean-spring-ctx.xml" })
public class FactoryBeanXmlConfigIntegrationTest {
@Autowired
private Tool tool;
@Resource(name = "&tool")
private ToolFactory toolFactory;
@Test
public void testConstructWorkerByXml() {
assertThat(tool.getId(), equalTo(1));
assertThat(toolFactory.getFactoryId(), equalTo(9090));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigIntegrationTest.java | spring-core-3/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigIntegrationTest.java | package com.baeldung.factorybean;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FactoryBeanAppConfig.class)
public class FactoryBeanJavaConfigIntegrationTest {
@Autowired
private Tool tool;
@Resource(name = "&tool")
private ToolFactory toolFactory;
@Test
public void testConstructWorkerByJava() {
assertThat(tool.getId(), equalTo(2));
assertThat(toolFactory.getFactoryId(), equalTo(7070));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java | spring-core-3/src/test/java/com/baeldung/customscope/TenantScopeIntegrationTest.java | package com.baeldung.customscope;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TenantScopeIntegrationTest {
@Test
public final void whenRegisterScopeAndBeans_thenContextContainsFooAndBar() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
try {
ctx.register(TenantScopeConfig.class);
ctx.register(TenantBeansConfig.class);
ctx.refresh();
TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class);
foo.sayHello();
TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class);
bar.sayHello();
Map<String, TenantBean> foos = ctx.getBeansOfType(TenantBean.class);
assertThat(foo, not(equalTo(bar)));
assertThat(foos.size(), equalTo(2));
assertTrue(foos.containsValue(foo));
assertTrue(foos.containsValue(bar));
BeanDefinition fooDefinition = ctx.getBeanDefinition("foo");
BeanDefinition barDefinition = ctx.getBeanDefinition("bar");
assertThat(fooDefinition.getScope(), equalTo("tenant"));
assertThat(barDefinition.getScope(), equalTo("tenant"));
} finally {
ctx.close();
}
}
@Test
public final void whenComponentScan_thenContextContainsFooAndBar() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
try {
ctx.scan("com.baeldung.customscope");
ctx.refresh();
TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class);
foo.sayHello();
TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class);
bar.sayHello();
Map<String, TenantBean> foos = ctx.getBeansOfType(TenantBean.class);
assertThat(foo, not(equalTo(bar)));
assertThat(foos.size(), equalTo(2));
assertTrue(foos.containsValue(foo));
assertTrue(foos.containsValue(bar));
BeanDefinition fooDefinition = ctx.getBeanDefinition("foo");
BeanDefinition barDefinition = ctx.getBeanDefinition("bar");
assertThat(fooDefinition.getScope(), equalTo("tenant"));
assertThat(barDefinition.getScope(), equalTo("tenant"));
} finally {
ctx.close();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java | spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java | package com.baeldung.getbean;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class GetBeanByNameWithConstructorParametersUnitTest {
private ApplicationContext context;
@BeforeAll
void setup() {
context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
}
@Test
void whenGivenCorrectName_thenShouldReturnBeanWithSpecifiedName() {
Tiger tiger = (Tiger) context.getBean("tiger", "Siberian");
assertEquals("Siberian", tiger.getName());
}
@Test
void whenGivenCorrectNameOrAlias_shouldReturnBeanWithSpecifiedName() {
Tiger tiger = (Tiger) context.getBean("tiger", "Siberian");
Tiger secondTiger = (Tiger) context.getBean("tiger", "Striped");
assertEquals("Siberian", tiger.getName());
assertEquals("Striped", secondTiger.getName());
}
@Test
void whenNoArgumentSpecifiedForPrototypeBean_thenShouldThrowException() {
assertThrows(UnsatisfiedDependencyException.class, () -> {
Tiger tiger = (Tiger) context.getBean("tiger");
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java | spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java | package com.baeldung.getbean;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class GetBeanByNameAndTypeUnitTest {
private ApplicationContext context;
@BeforeAll
void setup() {
context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
}
@Test
void whenSpecifiedMatchingNameAndType_thenShouldReturnRelatedBean() {
Lion lion = context.getBean("lion", Lion.class);
assertEquals("Hardcoded lion name", lion.getName());
}
@Test
void whenSpecifiedNotMatchingNameAndType_thenShouldThrowException() {
assertThrows(BeanNotOfRequiredTypeException.class, () -> context.getBean("lion", Tiger.class));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java | spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java | package com.baeldung.getbean;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class GetBeanByTypeUnitTest {
private ApplicationContext context;
@BeforeAll
void setup() {
context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
}
@Test
void whenGivenExistingUniqueType_thenShouldReturnRelatedBean() {
Lion lion = context.getBean(Lion.class);
assertNotNull(lion);
}
@Test
void whenGivenAmbiguousType_thenShouldThrowException() {
assertThrows(NoUniqueBeanDefinitionException.class, () -> context.getBean(AnnotationConfig.Animal.class));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java | spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java | package com.baeldung.getbean;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.jupiter.api.Assertions.assertEquals;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class GetBeanByTypeWithConstructorParametersUnitTest {
private ApplicationContext context;
@BeforeAll
void setup() {
context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
}
@Test
void whenGivenExistingTypeAndValidParameters_thenShouldReturnRelatedBean() {
Tiger tiger = context.getBean(Tiger.class, "Shere Khan");
assertEquals("Shere Khan", tiger.getName());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java | spring-core-3/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java | package com.baeldung.getbean;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class GetBeanByNameUnitTest {
private ApplicationContext context;
@BeforeAll
void setup() {
context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
}
@Test
void whenGivenExistingBeanName_shouldReturnThatBean() {
Object lion = context.getBean("lion");
assertEquals(lion.getClass(), Lion.class);
}
@Test
void whenGivenNonExistingBeanName_shouldThrowException() {
assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean("non-existing"));
}
@Test
void whenCastingToWrongType_thenShouldThrowException() {
assertThrows(ClassCastException.class, () -> {
Tiger tiger = (Tiger) context.getBean("lion");
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java | spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java | package com.baeldung.ioccontainer;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.baeldung.ioccontainer.bean.CustomBeanFactoryPostProcessor;
import com.baeldung.ioccontainer.bean.CustomBeanPostProcessor;
import com.baeldung.ioccontainer.bean.Student;
public class IOCContainerAppUnitTest {
@BeforeEach
@AfterEach
public void resetInstantiationFlag() {
Student.setBeanInstantiated(false);
CustomBeanPostProcessor.setBeanPostProcessorRegistered(false);
CustomBeanFactoryPostProcessor.setBeanFactoryPostProcessorRegistered(false);
}
@Test
public void whenBFInitialized_thenStudentNotInitialized() {
Resource res = new ClassPathResource("ioc-container-difference-example.xml");
BeanFactory factory = new XmlBeanFactory(res);
assertFalse(Student.isBeanInstantiated());
}
@Test
public void whenBFInitialized_thenStudentInitialized() {
Resource res = new ClassPathResource("ioc-container-difference-example.xml");
BeanFactory factory = new XmlBeanFactory(res);
Student student = (Student) factory.getBean("student");
assertTrue(Student.isBeanInstantiated());
}
@Test
public void whenAppContInitialized_thenStudentInitialized() {
ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml");
assertTrue(Student.isBeanInstantiated());
}
@Test
public void whenBFInitialized_thenBFPProcessorAndBPProcessorNotRegAutomatically() {
Resource res = new ClassPathResource("ioc-container-difference-example.xml");
ConfigurableListableBeanFactory factory = new XmlBeanFactory(res);
assertFalse(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered());
assertFalse(CustomBeanPostProcessor.isBeanPostProcessorRegistered());
}
@Test
public void whenBFPostProcessorAndBPProcessorRegisteredManually_thenReturnTrue() {
Resource res = new ClassPathResource("ioc-container-difference-example.xml");
ConfigurableListableBeanFactory factory = new XmlBeanFactory(res);
CustomBeanFactoryPostProcessor beanFactoryPostProcessor = new CustomBeanFactoryPostProcessor();
beanFactoryPostProcessor.postProcessBeanFactory(factory);
assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered());
CustomBeanPostProcessor beanPostProcessor = new CustomBeanPostProcessor();
factory.addBeanPostProcessor(beanPostProcessor);
Student student = (Student) factory.getBean("student");
assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered());
}
@Test
public void whenAppContInitialized_thenBFPostProcessorAndBPostProcessorRegisteredAutomatically() {
ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml");
assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered());
assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/beanfactory/Employee.java | spring-core-3/src/main/java/com/baeldung/beanfactory/Employee.java | package com.baeldung.beanfactory;
public class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java | spring-core-3/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java | package com.baeldung.factorybean;
import org.springframework.beans.factory.config.AbstractFactoryBean;
public class NonSingleToolFactory extends AbstractFactoryBean<Tool> {
private int factoryId;
private int toolId;
public NonSingleToolFactory() {
setSingleton(false);
}
@Override
public Class<?> getObjectType() {
return Tool.class;
}
@Override
protected Tool createInstance() throws Exception {
return new Tool(toolId);
}
public int getFactoryId() {
return factoryId;
}
public void setFactoryId(int factoryId) {
this.factoryId = factoryId;
}
public int getToolId() {
return toolId;
}
public void setToolId(int toolId) {
this.toolId = toolId;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/factorybean/ToolFactory.java | spring-core-3/src/main/java/com/baeldung/factorybean/ToolFactory.java | package com.baeldung.factorybean;
import org.springframework.beans.factory.FactoryBean;
public class ToolFactory implements FactoryBean<Tool> {
private int factoryId;
private int toolId;
@Override
public Tool getObject() throws Exception {
return new Tool(toolId);
}
@Override
public Class<?> getObjectType() {
return Tool.class;
}
@Override
public boolean isSingleton() {
return false;
}
public int getFactoryId() {
return factoryId;
}
public void setFactoryId(int factoryId) {
this.factoryId = factoryId;
}
public int getToolId() {
return toolId;
}
public void setToolId(int toolId) {
this.toolId = toolId;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/factorybean/SingleToolFactory.java | spring-core-3/src/main/java/com/baeldung/factorybean/SingleToolFactory.java | package com.baeldung.factorybean;
import org.springframework.beans.factory.config.AbstractFactoryBean;
//no need to set singleton property because default value is true
public class SingleToolFactory extends AbstractFactoryBean<Tool> {
private int factoryId;
private int toolId;
@Override
public Class<?> getObjectType() {
return Tool.class;
}
@Override
protected Tool createInstance() throws Exception {
return new Tool(toolId);
}
public int getFactoryId() {
return factoryId;
}
public void setFactoryId(int factoryId) {
this.factoryId = factoryId;
}
public int getToolId() {
return toolId;
}
public void setToolId(int toolId) {
this.toolId = toolId;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/factorybean/Tool.java | spring-core-3/src/main/java/com/baeldung/factorybean/Tool.java | package com.baeldung.factorybean;
public class Tool {
private int id;
public Tool() {
}
public Tool(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java | spring-core-3/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java | package com.baeldung.factorybean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FactoryBeanAppConfig {
@Bean(name = "tool")
public ToolFactory toolFactory() {
ToolFactory factory = new ToolFactory();
factory.setFactoryId(7070);
factory.setToolId(2);
return factory;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/customscope/TenantScopeConfig.java | spring-core-3/src/main/java/com/baeldung/customscope/TenantScopeConfig.java | package com.baeldung.customscope;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TenantScopeConfig {
@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
return new TenantBeanFactoryPostProcessor();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/customscope/TenantBeansConfig.java | spring-core-3/src/main/java/com/baeldung/customscope/TenantBeansConfig.java | package com.baeldung.customscope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class TenantBeansConfig {
@Scope(scopeName = "tenant")
@Bean
public TenantBean foo() {
return new TenantBean("foo");
}
@Scope(scopeName = "tenant")
@Bean
public TenantBean bar() {
return new TenantBean("bar");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/customscope/TenantScope.java | spring-core-3/src/main/java/com/baeldung/customscope/TenantScope.java | package com.baeldung.customscope;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
public class TenantScope implements Scope {
private Map<String, Object> scopedObjects = Collections.synchronizedMap(new HashMap<String, Object>());
private Map<String, Runnable> destructionCallbacks = Collections.synchronizedMap(new HashMap<String, Runnable>());
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
if (!scopedObjects.containsKey(name)) {
scopedObjects.put(name, objectFactory.getObject());
}
return scopedObjects.get(name);
}
@Override
public Object remove(String name) {
destructionCallbacks.remove(name);
return scopedObjects.remove(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
destructionCallbacks.put(name, callback);
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return "tenant";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java | spring-core-3/src/main/java/com/baeldung/customscope/TenantBeanFactoryPostProcessor.java | package com.baeldung.customscope;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public class TenantBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
factory.registerScope("tenant", new TenantScope());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/customscope/TenantBean.java | spring-core-3/src/main/java/com/baeldung/customscope/TenantBean.java | package com.baeldung.customscope;
public class TenantBean {
private final String name;
public TenantBean(String name) {
this.name = name;
}
public void sayHello() {
System.out.println(String.format("Hello from %s of type %s", this.name, this.getClass().getName()));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/getbean/Lion.java | spring-core-3/src/main/java/com/baeldung/getbean/Lion.java | package com.baeldung.getbean;
class Lion implements AnnotationConfig.Animal {
private String name;
Lion(String name) {
this.name = name;
}
String getName() {
return name;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/getbean/AnnotationConfig.java | spring-core-3/src/main/java/com/baeldung/getbean/AnnotationConfig.java | package com.baeldung.getbean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
class AnnotationConfig {
@Bean(name = {"tiger", "kitty"})
@Scope(value = "prototype")
Tiger getTiger(String name) {
return new Tiger(name);
}
@Bean(name = "lion")
Lion getLion() {
return new Lion("Hardcoded lion name");
}
interface Animal {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/getbean/Tiger.java | spring-core-3/src/main/java/com/baeldung/getbean/Tiger.java | package com.baeldung.getbean;
class Tiger implements AnnotationConfig.Animal {
private String name;
Tiger(String name) {
this.name = name;
}
String getName() {
return name;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java | spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java | package com.baeldung.ioccontainer.bean;
public class Student {
private static boolean isBeanInstantiated = false;
public void postConstruct() {
setBeanInstantiated(true);
}
public static boolean isBeanInstantiated() {
return isBeanInstantiated;
}
public static void setBeanInstantiated(boolean isBeanInstantiated) {
Student.isBeanInstantiated = isBeanInstantiated;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java | spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java | package com.baeldung.ioccontainer.bean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
private static boolean isBeanFactoryPostProcessorRegistered = false;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory){
setBeanFactoryPostProcessorRegistered(true);
}
public static boolean isBeanFactoryPostProcessorRegistered() {
return isBeanFactoryPostProcessorRegistered;
}
public static void setBeanFactoryPostProcessorRegistered(boolean isBeanFactoryPostProcessorRegistered) {
CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered = isBeanFactoryPostProcessorRegistered;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java | spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java | package com.baeldung.ioccontainer.bean;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class CustomBeanPostProcessor implements BeanPostProcessor {
private static boolean isBeanPostProcessorRegistered = false;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName){
setBeanPostProcessorRegistered(true);
return bean;
}
public static boolean isBeanPostProcessorRegistered() {
return isBeanPostProcessorRegistered;
}
public static void setBeanPostProcessorRegistered(boolean isBeanPostProcessorRegistered) {
CustomBeanPostProcessor.isBeanPostProcessorRegistered = isBeanPostProcessorRegistered;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/IntegrationTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/IntegrationTest.java | package com.baeldung.jhipster8;
import com.baeldung.jhipster8.config.AsyncSyncConfiguration;
import com.baeldung.jhipster8.config.EmbeddedSQL;
import com.baeldung.jhipster8.config.JacksonConfiguration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.test.context.SpringBootTest;
/**
* Base composite annotation for integration tests.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(classes = { Jhipster8MonolithicApp.class, JacksonConfiguration.class, AsyncSyncConfiguration.class })
@EmbeddedSQL
public @interface IntegrationTest {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/TechnicalStructureTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/TechnicalStructureTest.java | package com.baeldung.jhipster8;
import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;
import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
@AnalyzeClasses(packagesOf = Jhipster8MonolithicApp.class, importOptions = DoNotIncludeTests.class)
class TechnicalStructureTest {
// prettier-ignore
@ArchTest
static final ArchRule respectsTechnicalArchitectureLayers = layeredArchitecture()
.consideringAllDependencies()
.layer("Config").definedBy("..config..")
.layer("Web").definedBy("..web..")
.optionalLayer("Service").definedBy("..service..")
.layer("Security").definedBy("..security..")
.optionalLayer("Persistence").definedBy("..repository..")
.layer("Domain").definedBy("..domain..")
.whereLayer("Config").mayNotBeAccessedByAnyLayer()
.whereLayer("Web").mayOnlyBeAccessedByLayers("Config")
.whereLayer("Service").mayOnlyBeAccessedByLayers("Web", "Config")
.whereLayer("Security").mayOnlyBeAccessedByLayers("Config", "Service", "Web")
.whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service", "Security", "Web", "Config")
.whereLayer("Domain").mayOnlyBeAccessedByLayers("Persistence", "Service", "Security", "Web", "Config")
.ignoreDependency(belongToAnyOf(Jhipster8MonolithicApp.class), alwaysTrue())
.ignoreDependency(alwaysTrue(), belongToAnyOf(
com.baeldung.jhipster8.config.Constants.class,
com.baeldung.jhipster8.config.ApplicationProperties.class
));
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/management/SecurityMetersServiceTests.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/management/SecurityMetersServiceTests.java | package com.baeldung.jhipster8.management;
import static org.assertj.core.api.Assertions.assertThat;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.Collection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class SecurityMetersServiceTests {
private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens";
private MeterRegistry meterRegistry;
private SecurityMetersService securityMetersService;
@BeforeEach
public void setup() {
meterRegistry = new SimpleMeterRegistry();
securityMetersService = new SecurityMetersService(meterRegistry);
}
@Test
void testInvalidTokensCountersByCauseAreCreated() {
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter();
Collection<Counter> counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters();
assertThat(counters).hasSize(4);
}
@Test
void testCountMethodsShouldBeBoundToCorrectCounters() {
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isZero();
securityMetersService.trackTokenExpired();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isZero();
securityMetersService.trackTokenUnsupported();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isZero();
securityMetersService.trackTokenInvalidSignature();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isZero();
securityMetersService.trackTokenMalformed();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(1);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/service/MailServiceIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/service/MailServiceIT.java | package com.baeldung.jhipster8.service;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.config.Constants;
import com.baeldung.jhipster8.domain.User;
import jakarta.mail.Multipart;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import tech.jhipster.config.JHipsterProperties;
/**
* Integration tests for {@link MailService}.
*/
@IntegrationTest
class MailServiceIT {
private static final String[] languages = {
// jhipster-needle-i18n-language-constant - JHipster will add/remove languages in this array
};
private static final Pattern PATTERN_LOCALE_3 = Pattern.compile("([a-z]{2})-([a-zA-Z]{4})-([a-z]{2})");
private static final Pattern PATTERN_LOCALE_2 = Pattern.compile("([a-z]{2})-([a-z]{2})");
@Autowired
private JHipsterProperties jHipsterProperties;
@MockBean
private JavaMailSender javaMailSender;
@Captor
private ArgumentCaptor<MimeMessage> messageCaptor;
@Autowired
private MailService mailService;
@BeforeEach
public void setup() {
doNothing().when(javaMailSender).send(any(MimeMessage.class));
when(javaMailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null));
}
@Test
void testSendEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com");
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(String.class);
assertThat(message.getContent()).hasToString("testContent");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
void testSendHtmlEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com");
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(String.class);
assertThat(message.getContent()).hasToString("testContent");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendMultipartEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com");
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos).hasToString("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
void testSendMultipartHtmlEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com");
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos).hasToString("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendEmailFromTemplate() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title");
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("test title");
assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail());
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>test title, http://127.0.0.1:8080, john</html>\n");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendActivationEmail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendActivationEmail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail());
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testCreationEmail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendCreationEmail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail());
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendPasswordResetMail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendPasswordResetMail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail());
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendEmailWithException() {
doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class));
try {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false);
} catch (Exception e) {
fail("Exception shouldn't have been thrown");
}
}
@Test
void testSendLocalizedEmailForAllSupportedLanguages() throws Exception {
User user = new User();
user.setLogin("john");
user.setEmail("john.doe@example.com");
for (String langKey : languages) {
user.setLangKey(langKey);
mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title");
verify(javaMailSender, atLeastOnce()).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
String propertyFilePath = "i18n/messages_" + getMessageSourceSuffixForLanguage(langKey) + ".properties";
URL resource = this.getClass().getClassLoader().getResource(propertyFilePath);
File file = new File(new URI(resource.getFile()).getPath());
Properties properties = new Properties();
properties.load(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")));
String emailTitle = (String) properties.get("email.test.title");
assertThat(message.getSubject()).isEqualTo(emailTitle);
assertThat(message.getContent().toString()).isEqualToNormalizingNewlines(
"<html>" + emailTitle + ", http://127.0.0.1:8080, john</html>\n"
);
}
}
/**
* Convert a lang key to the Java locale.
*/
private String getMessageSourceSuffixForLanguage(String langKey) {
String javaLangKey = langKey;
Matcher matcher2 = PATTERN_LOCALE_2.matcher(langKey);
if (matcher2.matches()) {
javaLangKey = matcher2.group(1) + "_" + matcher2.group(2).toUpperCase();
}
Matcher matcher3 = PATTERN_LOCALE_3.matcher(langKey);
if (matcher3.matches()) {
javaLangKey = matcher3.group(1) + "_" + matcher3.group(2) + "_" + matcher3.group(3).toUpperCase();
}
return javaLangKey;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/service/UserServiceIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/service/UserServiceIT.java | package com.baeldung.jhipster8.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.repository.UserRepository;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.auditing.AuditingHandler;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.transaction.annotation.Transactional;
import tech.jhipster.security.RandomUtil;
/**
* Integration tests for {@link UserService}.
*/
@IntegrationTest
@Transactional
class UserServiceIT {
private static final String DEFAULT_LOGIN = "johndoe";
private static final String DEFAULT_EMAIL = "johndoe@localhost";
private static final String DEFAULT_FIRSTNAME = "john";
private static final String DEFAULT_LASTNAME = "doe";
private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
private static final String DEFAULT_LANGKEY = "dummy";
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
@Autowired
private AuditingHandler auditingHandler;
@MockBean
private DateTimeProvider dateTimeProvider;
private User user;
@BeforeEach
public void init() {
user = new User();
user.setLogin(DEFAULT_LOGIN);
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setEmail(DEFAULT_EMAIL);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now()));
auditingHandler.setDateTimeProvider(dateTimeProvider);
}
@Test
@Transactional
void assertThatUserMustExistToResetPassword() {
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.requestPasswordReset("invalid.login@localhost");
assertThat(maybeUser).isNotPresent();
maybeUser = userService.requestPasswordReset(user.getEmail());
assertThat(maybeUser).isPresent();
assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail());
assertThat(maybeUser.orElse(null).getResetDate()).isNotNull();
assertThat(maybeUser.orElse(null).getResetKey()).isNotNull();
}
@Test
@Transactional
void assertThatOnlyActivatedUserCanRequestPasswordReset() {
user.setActivated(false);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
void assertThatResetKeyMustNotBeOlderThan24Hours() {
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
void assertThatResetKeyMustBeValid() {
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey("1234");
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
void assertThatUserCanResetPassword() {
String oldPassword = user.getPassword();
Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isPresent();
assertThat(maybeUser.orElse(null).getResetDate()).isNull();
assertThat(maybeUser.orElse(null).getResetKey()).isNull();
assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword);
userRepository.delete(user);
}
@Test
@Transactional
void assertThatNotActivatedUsersWithNotNullActivationKeyCreatedBefore3DaysAreDeleted() {
Instant now = Instant.now();
when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS)));
user.setActivated(false);
user.setActivationKey(RandomStringUtils.random(20));
User dbUser = userRepository.saveAndFlush(user);
dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
userRepository.saveAndFlush(user);
Instant threeDaysAgo = now.minus(3, ChronoUnit.DAYS);
List<User> users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo);
assertThat(users).isNotEmpty();
userService.removeNotActivatedUsers();
users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo);
assertThat(users).isEmpty();
}
@Test
@Transactional
void assertThatNotActivatedUsersWithNullActivationKeyCreatedBefore3DaysAreNotDeleted() {
Instant now = Instant.now();
when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS)));
user.setActivated(false);
User dbUser = userRepository.saveAndFlush(user);
dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
userRepository.saveAndFlush(user);
Instant threeDaysAgo = now.minus(3, ChronoUnit.DAYS);
List<User> users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo);
assertThat(users).isEmpty();
userService.removeNotActivatedUsers();
Optional<User> maybeDbUser = userRepository.findById(dbUser.getId());
assertThat(maybeDbUser).contains(dbUser);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/service/mapper/UserMapperUnitTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/service/mapper/UserMapperUnitTest.java | package com.baeldung.jhipster8.service.mapper;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.service.dto.AdminUserDTO;
import com.baeldung.jhipster8.service.dto.UserDTO;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link UserMapper}.
*/
class UserMapperUnitTest {
private static final String DEFAULT_LOGIN = "johndoe";
private static final Long DEFAULT_ID = 1L;
private UserMapper userMapper;
private User user;
private AdminUserDTO userDto;
@BeforeEach
public void init() {
userMapper = new UserMapper();
user = new User();
user.setLogin(DEFAULT_LOGIN);
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setEmail("johndoe@localhost");
user.setFirstName("john");
user.setLastName("doe");
user.setImageUrl("image_url");
user.setLangKey("en");
userDto = new AdminUserDTO(user);
}
@Test
void usersToUserDTOsShouldMapOnlyNonNullUsers() {
List<User> users = new ArrayList<>();
users.add(user);
users.add(null);
List<UserDTO> userDTOS = userMapper.usersToUserDTOs(users);
assertThat(userDTOS).isNotEmpty().size().isEqualTo(1);
}
@Test
void userDTOsToUsersShouldMapOnlyNonNullUsers() {
List<AdminUserDTO> usersDto = new ArrayList<>();
usersDto.add(userDto);
usersDto.add(null);
List<User> users = userMapper.userDTOsToUsers(usersDto);
assertThat(users).isNotEmpty().size().isEqualTo(1);
}
@Test
void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain() {
Set<String> authoritiesAsString = new HashSet<>();
authoritiesAsString.add("ADMIN");
userDto.setAuthorities(authoritiesAsString);
List<AdminUserDTO> usersDto = new ArrayList<>();
usersDto.add(userDto);
List<User> users = userMapper.userDTOsToUsers(usersDto);
assertThat(users).isNotEmpty().size().isEqualTo(1);
assertThat(users.get(0).getAuthorities()).isNotNull();
assertThat(users.get(0).getAuthorities()).isNotEmpty();
assertThat(users.get(0).getAuthorities().iterator().next().getName()).isEqualTo("ADMIN");
}
@Test
void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() {
userDto.setAuthorities(null);
List<AdminUserDTO> usersDto = new ArrayList<>();
usersDto.add(userDto);
List<User> users = userMapper.userDTOsToUsers(usersDto);
assertThat(users).isNotEmpty().size().isEqualTo(1);
assertThat(users.get(0).getAuthorities()).isNotNull();
assertThat(users.get(0).getAuthorities()).isEmpty();
}
@Test
void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() {
Set<String> authoritiesAsString = new HashSet<>();
authoritiesAsString.add("ADMIN");
userDto.setAuthorities(authoritiesAsString);
User user = userMapper.userDTOToUser(userDto);
assertThat(user).isNotNull();
assertThat(user.getAuthorities()).isNotNull();
assertThat(user.getAuthorities()).isNotEmpty();
assertThat(user.getAuthorities().iterator().next().getName()).isEqualTo("ADMIN");
}
@Test
void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() {
userDto.setAuthorities(null);
User user = userMapper.userDTOToUser(userDto);
assertThat(user).isNotNull();
assertThat(user.getAuthorities()).isNotNull();
assertThat(user.getAuthorities()).isEmpty();
}
@Test
void userDTOToUserMapWithNullUserShouldReturnNull() {
assertThat(userMapper.userDTOToUser(null)).isNull();
}
@Test
void testUserFromId() {
assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID);
assertThat(userMapper.userFromId(null)).isNull();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/domain/AssertUtils.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/domain/AssertUtils.java | package com.baeldung.jhipster8.domain;
import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Comparator;
public class AssertUtils {
public static Comparator<ZonedDateTime> zonedDataTimeSameInstant = Comparator.nullsFirst(
(e1, a2) -> e1.withZoneSameInstant(ZoneOffset.UTC).compareTo(a2.withZoneSameInstant(ZoneOffset.UTC))
);
public static Comparator<BigDecimal> bigDecimalCompareTo = Comparator.nullsFirst((e1, a2) -> e1.compareTo(a2));
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/domain/AuthorityUnitTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/domain/AuthorityUnitTest.java | package com.baeldung.jhipster8.domain;
import static com.baeldung.jhipster8.domain.AuthorityTestSamples.*;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.jhipster8.web.rest.TestUtil;
import org.junit.jupiter.api.Test;
class AuthorityUnitTest {
@Test
void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Authority.class);
Authority authority1 = getAuthoritySample1();
Authority authority2 = new Authority();
assertThat(authority1).isNotEqualTo(authority2);
authority2.setName(authority1.getName());
assertThat(authority1).isEqualTo(authority2);
authority2 = getAuthoritySample2();
assertThat(authority1).isNotEqualTo(authority2);
}
@Test
void hashCodeVerifier() throws Exception {
Authority authority = new Authority();
assertThat(authority.hashCode()).isZero();
Authority authority1 = getAuthoritySample1();
authority.setName(authority1.getName());
assertThat(authority).hasSameHashCodeAs(authority1);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/domain/AuthorityAsserts.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/domain/AuthorityAsserts.java | package com.baeldung.jhipster8.domain;
import static org.assertj.core.api.Assertions.assertThat;
public class AuthorityAsserts {
/**
* Asserts that the entity has all properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityAllPropertiesEquals(Authority expected, Authority actual) {
assertAuthorityAutoGeneratedPropertiesEquals(expected, actual);
assertAuthorityAllUpdatablePropertiesEquals(expected, actual);
}
/**
* Asserts that the entity has all updatable properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityAllUpdatablePropertiesEquals(Authority expected, Authority actual) {
assertAuthorityUpdatableFieldsEquals(expected, actual);
assertAuthorityUpdatableRelationshipsEquals(expected, actual);
}
/**
* Asserts that the entity has all the auto generated properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityAutoGeneratedPropertiesEquals(Authority expected, Authority actual) {}
/**
* Asserts that the entity has all the updatable fields set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityUpdatableFieldsEquals(Authority expected, Authority actual) {
assertThat(expected)
.as("Verify Authority relevant properties")
.satisfies(e -> assertThat(e.getName()).as("check name").isEqualTo(actual.getName()));
}
/**
* Asserts that the entity has all the updatable relationships set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityUpdatableRelationshipsEquals(Authority expected, Authority actual) {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/domain/AuthorityTestSamples.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/domain/AuthorityTestSamples.java | package com.baeldung.jhipster8.domain;
import java.util.UUID;
public class AuthorityTestSamples {
public static Authority getAuthoritySample1() {
return new Authority().name("name1");
}
public static Authority getAuthoritySample2() {
return new Authority().name("name2");
}
public static Authority getAuthorityRandomSampleGenerator() {
return new Authority().name(UUID.randomUUID().toString());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/repository/timezone/DateTimeWrapper.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/repository/timezone/DateTimeWrapper.java | package com.baeldung.jhipster8.repository.timezone;
import jakarta.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;
@Entity
@Table(name = "jhi_date_time_wrapper")
public class DateTimeWrapper implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "instant")
private Instant instant;
@Column(name = "local_date_time")
private LocalDateTime localDateTime;
@Column(name = "offset_date_time")
private OffsetDateTime offsetDateTime;
@Column(name = "zoned_date_time")
private ZonedDateTime zonedDateTime;
@Column(name = "local_time")
private LocalTime localTime;
@Column(name = "offset_time")
private OffsetTime offsetTime;
@Column(name = "local_date")
private LocalDate localDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
}
public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
this.offsetDateTime = offsetDateTime;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
public LocalTime getLocalTime() {
return localTime;
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
public OffsetTime getOffsetTime() {
return offsetTime;
}
public void setOffsetTime(OffsetTime offsetTime) {
this.offsetTime = offsetTime;
}
public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DateTimeWrapper dateTimeWrapper = (DateTimeWrapper) o;
return !(dateTimeWrapper.getId() == null || getId() == null) && Objects.equals(getId(), dateTimeWrapper.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
// prettier-ignore
@Override
public String toString() {
return "TimeZoneTest{" +
"id=" + id +
", instant=" + instant +
", localDateTime=" + localDateTime +
", offsetDateTime=" + offsetDateTime +
", zonedDateTime=" + zonedDateTime +
'}';
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/repository/timezone/DateTimeWrapperRepository.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/repository/timezone/DateTimeWrapperRepository.java | package com.baeldung.jhipster8.repository.timezone;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the {@link DateTimeWrapper} entity.
*/
@Repository
public interface DateTimeWrapperRepository extends JpaRepository<DateTimeWrapper, Long> {}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/DomainUserDetailsServiceIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/DomainUserDetailsServiceIT.java | package com.baeldung.jhipster8.security;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.repository.UserRepository;
import java.util.Locale;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.transaction.annotation.Transactional;
/**
* Integrations tests for {@link DomainUserDetailsService}.
*/
@Transactional
@IntegrationTest
class DomainUserDetailsServiceIT {
private static final String USER_ONE_LOGIN = "test-user-one";
private static final String USER_ONE_EMAIL = "test-user-one@localhost";
private static final String USER_TWO_LOGIN = "test-user-two";
private static final String USER_TWO_EMAIL = "test-user-two@localhost";
private static final String USER_THREE_LOGIN = "test-user-three";
private static final String USER_THREE_EMAIL = "test-user-three@localhost";
@Autowired
private UserRepository userRepository;
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService domainUserDetailsService;
@BeforeEach
public void init() {
User userOne = new User();
userOne.setLogin(USER_ONE_LOGIN);
userOne.setPassword(RandomStringUtils.randomAlphanumeric(60));
userOne.setActivated(true);
userOne.setEmail(USER_ONE_EMAIL);
userOne.setFirstName("userOne");
userOne.setLastName("doe");
userOne.setLangKey("en");
userRepository.save(userOne);
User userTwo = new User();
userTwo.setLogin(USER_TWO_LOGIN);
userTwo.setPassword(RandomStringUtils.randomAlphanumeric(60));
userTwo.setActivated(true);
userTwo.setEmail(USER_TWO_EMAIL);
userTwo.setFirstName("userTwo");
userTwo.setLastName("doe");
userTwo.setLangKey("en");
userRepository.save(userTwo);
User userThree = new User();
userThree.setLogin(USER_THREE_LOGIN);
userThree.setPassword(RandomStringUtils.randomAlphanumeric(60));
userThree.setActivated(false);
userThree.setEmail(USER_THREE_EMAIL);
userThree.setFirstName("userThree");
userThree.setLastName("doe");
userThree.setLangKey("en");
userRepository.save(userThree);
}
@Test
void assertThatUserCanBeFoundByLogin() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN);
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test
void assertThatUserCanBeFoundByLoginIgnoreCase() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH));
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test
void assertThatUserCanBeFoundByEmail() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL);
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN);
}
@Test
void assertThatUserCanBeFoundByEmailIgnoreCase() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH));
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN);
}
@Test
void assertThatEmailIsPrioritizedOverLogin() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL);
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test
void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() {
assertThatExceptionOfType(UserNotActivatedException.class).isThrownBy(
() -> domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN)
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/SecurityUtilsUnitTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/SecurityUtilsUnitTest.java | package com.baeldung.jhipster8.security;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Test class for the {@link SecurityUtils} utility class.
*/
class SecurityUtilsUnitTest {
@BeforeEach
@AfterEach
void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
void testGetCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
Optional<String> login = SecurityUtils.getCurrentUserLogin();
assertThat(login).contains("admin");
}
@Test
void testGetCurrentUserJWT() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token"));
SecurityContextHolder.setContext(securityContext);
Optional<String> jwt = SecurityUtils.getCurrentUserJWT();
assertThat(jwt).contains("token");
}
@Test
void testIsAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isTrue();
}
@Test
void testAnonymousIsNotAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isFalse();
}
@Test
void testHasCurrentUserThisAuthority() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
SecurityContextHolder.setContext(securityContext);
assertThat(SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER)).isTrue();
assertThat(SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)).isFalse();
}
@Test
void testHasCurrentUserAnyOfAuthorities() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
SecurityContextHolder.setContext(securityContext);
assertThat(SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isTrue();
assertThat(SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isFalse();
}
@Test
void testHasCurrentUserNoneOfAuthorities() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
SecurityContextHolder.setContext(securityContext);
assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isFalse();
assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isTrue();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/jwt/AuthenticationIntegrationTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/jwt/AuthenticationIntegrationTest.java | package com.baeldung.jhipster8.security.jwt;
import com.baeldung.jhipster8.config.SecurityConfiguration;
import com.baeldung.jhipster8.config.SecurityJwtConfiguration;
import com.baeldung.jhipster8.config.WebConfigurer;
import com.baeldung.jhipster8.management.SecurityMetersService;
import com.baeldung.jhipster8.web.rest.AuthenticateController;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.test.context.SpringBootTest;
import tech.jhipster.config.JHipsterProperties;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(
properties = {
"jhipster.security.authentication.jwt.base64-secret=fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8",
"jhipster.security.authentication.jwt.token-validity-in-seconds=60000",
},
classes = {
JHipsterProperties.class,
WebConfigurer.class,
SecurityConfiguration.class,
SecurityJwtConfiguration.class,
SecurityMetersService.class,
AuthenticateController.class,
JwtAuthenticationTestUtils.class,
}
)
public @interface AuthenticationIntegrationTest {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/jwt/TokenAuthenticationSecurityMetersIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/jwt/TokenAuthenticationSecurityMetersIT.java | package com.baeldung.jhipster8.security.jwt;
import static com.baeldung.jhipster8.security.jwt.JwtAuthenticationTestUtils.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@AutoConfigureMockMvc
@AuthenticationIntegrationTest
class TokenAuthenticationSecurityMetersIT {
private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens";
@Autowired
private MockMvc mvc;
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Autowired
private MeterRegistry meterRegistry;
@Test
void testValidTokenShouldNotCountAnything() throws Exception {
Collection<Counter> counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters();
var count = aggregate(counters);
tryToAuthenticate(createValidToken(jwtKey));
assertThat(aggregate(counters)).isEqualTo(count);
}
@Test
void testTokenExpiredCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count();
tryToAuthenticate(createExpiredToken(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(count + 1);
}
@Test
void testTokenSignatureInvalidCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count();
tryToAuthenticate(createTokenWithDifferentSignature());
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo(
count + 1
);
}
@Test
void testTokenMalformedCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count();
tryToAuthenticate(createSignedInvalidJwt(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1);
}
@Test
void testTokenInvalidCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count();
tryToAuthenticate(createInvalidToken(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1);
}
private void tryToAuthenticate(String token) throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token));
}
private double aggregate(Collection<Counter> counters) {
return counters.stream().mapToDouble(Counter::count).sum();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/jwt/TokenAuthenticationIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/jwt/TokenAuthenticationIT.java | package com.baeldung.jhipster8.security.jwt;
import static com.baeldung.jhipster8.security.jwt.JwtAuthenticationTestUtils.*;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@AutoConfigureMockMvc
@AuthenticationIntegrationTest
class TokenAuthenticationIT {
@Autowired
private MockMvc mvc;
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Test
void testLoginWithValidToken() throws Exception {
expectOk(createValidToken(jwtKey));
}
@Test
void testReturnFalseWhenJWThasInvalidSignature() throws Exception {
expectUnauthorized(createTokenWithDifferentSignature());
}
@Test
void testReturnFalseWhenJWTisMalformed() throws Exception {
expectUnauthorized(createSignedInvalidJwt(jwtKey));
}
@Test
void testReturnFalseWhenJWTisExpired() throws Exception {
expectUnauthorized(createExpiredToken(jwtKey));
}
private void expectOk(String token) throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token)).andExpect(status().isOk());
}
private void expectUnauthorized(String token) throws Exception {
mvc
.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token))
.andExpect(status().isUnauthorized());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/jwt/JwtAuthenticationTestUtils.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/security/jwt/JwtAuthenticationTestUtils.java | package com.baeldung.jhipster8.security.jwt;
import static com.baeldung.jhipster8.security.SecurityUtils.AUTHORITIES_KEY;
import static com.baeldung.jhipster8.security.SecurityUtils.JWT_ALGORITHM;
import com.nimbusds.jose.jwk.source.ImmutableSecret;
import com.nimbusds.jose.util.Base64;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Instant;
import java.util.Collections;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
public class JwtAuthenticationTestUtils {
public static final String BEARER = "Bearer ";
@Bean
private HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
return new HandlerMappingIntrospector();
}
@Bean
private MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
public static String createValidToken(String jwtKey) {
return createValidTokenForUser(jwtKey, "anonymous");
}
public static String createValidTokenForUser(String jwtKey, String user) {
JwtEncoder encoder = jwtEncoder(jwtKey);
var now = Instant.now();
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(now)
.expiresAt(now.plusSeconds(60))
.subject(user)
.claims(customClaim -> customClaim.put(AUTHORITIES_KEY, Collections.singletonList("ROLE_ADMIN")))
.build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createTokenWithDifferentSignature() {
JwtEncoder encoder = jwtEncoder("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8");
var now = Instant.now();
var past = now.plusSeconds(60);
JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(now).expiresAt(past).subject("anonymous").build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createExpiredToken(String jwtKey) {
JwtEncoder encoder = jwtEncoder(jwtKey);
var now = Instant.now();
var past = now.minusSeconds(600);
JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(past).expiresAt(past.plusSeconds(1)).subject("anonymous").build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createInvalidToken(String jwtKey) {
return createValidToken(jwtKey).substring(1);
}
public static String createSignedInvalidJwt(String jwtKey) throws Exception {
return calculateHMAC("foo", jwtKey);
}
private static JwtEncoder jwtEncoder(String jwtKey) {
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey(jwtKey)));
}
private static SecretKey getSecretKey(String jwtKey) {
byte[] keyBytes = Base64.from(jwtKey).decode();
return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName());
}
private static String calculateHMAC(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.from(key).decode(), "HmacSHA512");
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(secretKeySpec);
return String.copyValueOf(Hex.encode(mac.doFinal(data.getBytes())));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/SqlTestContainer.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/SqlTestContainer.java | package com.baeldung.jhipster8.config;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.testcontainers.containers.JdbcDatabaseContainer;
public interface SqlTestContainer extends InitializingBean, DisposableBean {
JdbcDatabaseContainer<?> getTestContainer();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/MysqlTestContainer.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/MysqlTestContainer.java | package com.baeldung.jhipster8.config;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.containers.output.Slf4jLogConsumer;
public class MysqlTestContainer implements SqlTestContainer {
private static final Logger log = LoggerFactory.getLogger(MysqlTestContainer.class);
private MySQLContainer<?> mysqlContainer;
@Override
public void destroy() {
if (null != mysqlContainer && mysqlContainer.isRunning()) {
mysqlContainer.stop();
}
}
@Override
public void afterPropertiesSet() {
if (null == mysqlContainer) {
mysqlContainer = new MySQLContainer<>("mysql:8.3.0")
.withDatabaseName("jhipster8Monolithic")
.withTmpFs(Collections.singletonMap("/testtmpfs", "rw"))
.withLogConsumer(new Slf4jLogConsumer(log))
.withReuse(true);
}
if (!mysqlContainer.isRunning()) {
mysqlContainer.start();
}
}
@Override
public JdbcDatabaseContainer<?> getTestContainer() {
return mysqlContainer;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/CRLFLogConverterTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/CRLFLogConverterTest.java | package com.baeldung.jhipster8.config;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiElement;
class CRLFLogConverterTest {
@Test
void transformShouldReturnInputStringWhenMarkerListIsEmpty() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getMarkerList()).thenReturn(null);
when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger");
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
}
@Test
void transformShouldReturnInputStringWhenMarkersContainCRLFSafeMarker() {
ILoggingEvent event = mock(ILoggingEvent.class);
Marker marker = MarkerFactory.getMarker("CRLF_SAFE");
List<Marker> markers = Collections.singletonList(marker);
when(event.getMarkerList()).thenReturn(markers);
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
}
@Test
void transformShouldReturnInputStringWhenMarkersNotContainCRLFSafeMarker() {
ILoggingEvent event = mock(ILoggingEvent.class);
Marker marker = MarkerFactory.getMarker("CRLF_NOT_SAFE");
List<Marker> markers = Collections.singletonList(marker);
when(event.getMarkerList()).thenReturn(markers);
when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger");
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
}
@Test
void transformShouldReturnInputStringWhenLoggerIsSafe() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger");
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
}
@Test
void transformShouldReplaceNewlinesAndCarriageReturnsWithUnderscoreWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafe() {
ILoggingEvent event = mock(ILoggingEvent.class);
List<Marker> markers = Collections.emptyList();
when(event.getMarkerList()).thenReturn(markers);
when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger");
String input = "Test\ninput\rstring";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals("Test_input_string", result);
}
@Test
void transformShouldReplaceNewlinesAndCarriageReturnsWithAnsiStringWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafeAndAnsiElementIsNotNull() {
ILoggingEvent event = mock(ILoggingEvent.class);
List<Marker> markers = Collections.emptyList();
when(event.getMarkerList()).thenReturn(markers);
when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger");
String input = "Test\ninput\rstring";
CRLFLogConverter converter = new CRLFLogConverter();
converter.setOptionList(List.of("red"));
String result = converter.transform(event, input);
assertEquals("Test_input_string", result);
}
@Test
void isLoggerSafeShouldReturnTrueWhenLoggerNameStartsWithSafeLogger() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getLoggerName()).thenReturn("org.springframework.boot.autoconfigure.example.Logger");
CRLFLogConverter converter = new CRLFLogConverter();
boolean result = converter.isLoggerSafe(event);
assertTrue(result);
}
@Test
void isLoggerSafeShouldReturnFalseWhenLoggerNameDoesNotStartWithSafeLogger() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger");
CRLFLogConverter converter = new CRLFLogConverter();
boolean result = converter.isLoggerSafe(event);
assertFalse(result);
}
@Test
void testToAnsiString() {
CRLFLogConverter cut = new CRLFLogConverter();
AnsiElement ansiElement = AnsiColor.RED;
String result = cut.toAnsiString("input", ansiElement);
assertThat(result).isEqualTo("input");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/EmbeddedSQL.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/EmbeddedSQL.java | package com.baeldung.jhipster8.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EmbeddedSQL {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/SqlTestContainersSpringContextCustomizerFactory.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/SqlTestContainersSpringContextCustomizerFactory.java | package com.baeldung.jhipster8.config;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.ContextCustomizerFactory;
import org.springframework.test.context.MergedContextConfiguration;
import tech.jhipster.config.JHipsterConstants;
public class SqlTestContainersSpringContextCustomizerFactory implements ContextCustomizerFactory {
private Logger log = LoggerFactory.getLogger(SqlTestContainersSpringContextCustomizerFactory.class);
private static SqlTestContainer prodTestContainer;
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configAttributes) {
return new ContextCustomizer() {
@Override
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
TestPropertyValues testValues = TestPropertyValues.empty();
EmbeddedSQL sqlAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedSQL.class);
boolean usingTestProdProfile = Arrays.asList(context.getEnvironment().getActiveProfiles()).contains(
"test" + JHipsterConstants.SPRING_PROFILE_PRODUCTION
);
if (null != sqlAnnotation && usingTestProdProfile) {
log.debug("detected the EmbeddedSQL annotation on class {}", testClass.getName());
log.info("Warming up the sql database");
if (null == prodTestContainer) {
try {
Class<? extends SqlTestContainer> containerClass = (Class<? extends SqlTestContainer>) Class.forName(
this.getClass().getPackageName() + ".MysqlTestContainer"
);
prodTestContainer = beanFactory.createBean(containerClass);
beanFactory.registerSingleton(containerClass.getName(), prodTestContainer);
// ((DefaultListableBeanFactory)beanFactory).registerDisposableBean(containerClass.getName(), prodTestContainer);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
testValues = testValues.and(
"spring.datasource.url=" +
prodTestContainer.getTestContainer().getJdbcUrl() +
"?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&createDatabaseIfNotExist=true"
);
testValues = testValues.and("spring.datasource.username=" + prodTestContainer.getTestContainer().getUsername());
testValues = testValues.and("spring.datasource.password=" + prodTestContainer.getTestContainer().getPassword());
}
testValues.applyTo(context);
}
@Override
public int hashCode() {
return SqlTestContainer.class.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
return this.hashCode() == obj.hashCode();
}
};
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/StaticResourcesWebConfigurerTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/StaticResourcesWebConfigurerTest.java | package com.baeldung.jhipster8.config;
import static com.baeldung.jhipster8.config.StaticResourcesWebConfiguration.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.CacheControl;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import tech.jhipster.config.JHipsterDefaults;
import tech.jhipster.config.JHipsterProperties;
class StaticResourcesWebConfigurerTest {
public static final int MAX_AGE_TEST = 5;
public StaticResourcesWebConfiguration staticResourcesWebConfiguration;
private ResourceHandlerRegistry resourceHandlerRegistry;
private MockServletContext servletContext;
private WebApplicationContext applicationContext;
private JHipsterProperties props;
@BeforeEach
void setUp() {
servletContext = spy(new MockServletContext());
applicationContext = mock(WebApplicationContext.class);
resourceHandlerRegistry = spy(new ResourceHandlerRegistry(applicationContext, servletContext));
props = new JHipsterProperties();
staticResourcesWebConfiguration = spy(new StaticResourcesWebConfiguration(props));
}
@Test
void shouldAppendResourceHandlerAndInitializeIt() {
staticResourcesWebConfiguration.addResourceHandlers(resourceHandlerRegistry);
verify(resourceHandlerRegistry, times(1)).addResourceHandler(RESOURCE_PATHS);
verify(staticResourcesWebConfiguration, times(1)).initializeResourceHandler(any(ResourceHandlerRegistration.class));
for (String testingPath : RESOURCE_PATHS) {
assertThat(resourceHandlerRegistry.hasMappingForPattern(testingPath)).isTrue();
}
}
@Test
void shouldInitializeResourceHandlerWithCacheControlAndLocations() {
CacheControl ccExpected = CacheControl.maxAge(5, TimeUnit.DAYS).cachePublic();
when(staticResourcesWebConfiguration.getCacheControl()).thenReturn(ccExpected);
ResourceHandlerRegistration resourceHandlerRegistration = spy(new ResourceHandlerRegistration(RESOURCE_PATHS));
staticResourcesWebConfiguration.initializeResourceHandler(resourceHandlerRegistration);
verify(staticResourcesWebConfiguration, times(1)).getCacheControl();
verify(resourceHandlerRegistration, times(1)).setCacheControl(ccExpected);
verify(resourceHandlerRegistration, times(1)).addResourceLocations(RESOURCE_LOCATIONS);
}
@Test
void shouldCreateCacheControlBasedOnJhipsterDefaultProperties() {
CacheControl cacheExpected = CacheControl.maxAge(JHipsterDefaults.Http.Cache.timeToLiveInDays, TimeUnit.DAYS).cachePublic();
assertThat(staticResourcesWebConfiguration.getCacheControl())
.extracting(CacheControl::getHeaderValue)
.isEqualTo(cacheExpected.getHeaderValue());
}
@Test
void shouldCreateCacheControlWithSpecificConfigurationInProperties() {
props.getHttp().getCache().setTimeToLiveInDays(MAX_AGE_TEST);
CacheControl cacheExpected = CacheControl.maxAge(MAX_AGE_TEST, TimeUnit.DAYS).cachePublic();
assertThat(staticResourcesWebConfiguration.getCacheControl())
.extracting(CacheControl::getHeaderValue)
.isEqualTo(cacheExpected.getHeaderValue());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/AsyncSyncConfiguration.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/AsyncSyncConfiguration.java | package com.baeldung.jhipster8.config;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SyncTaskExecutor;
@Configuration
public class AsyncSyncConfiguration {
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
return new SyncTaskExecutor();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/WebConfigurerTestController.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/WebConfigurerTestController.java | package com.baeldung.jhipster8.config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebConfigurerTestController {
@GetMapping("/api/test-cors")
public void testCorsOnApiPath() {}
@GetMapping("/test/test-cors")
public void testCorsOnOtherPath() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/WebConfigurerTest.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/WebConfigurerTest.java | package com.baeldung.jhipster8.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import jakarta.servlet.*;
import java.io.File;
import java.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
/**
* Unit tests for the {@link WebConfigurer} class.
*/
class WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.class)).when(servletContext).addFilter(anyString(), any(Filter.class));
doReturn(mock(ServletRegistration.Dynamic.class)).when(servletContext).addServlet(anyString(), any(Servlet.class));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
void shouldCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html");
assertThat(container.getMimeMappings().get("json")).isEqualTo("application/json");
if (container.getDocumentRoot() != null) {
assertThat(container.getDocumentRoot()).isEqualTo(new File("target/classes/static/"));
}
}
@Test
void shouldCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("other.domain.com"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(
options("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")
)
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"))
.andExpect(header().string(HttpHeaders.VARY, "Origin"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc
.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
void shouldCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void shouldCorsFilterDeactivatedForNullAllowedOrigins() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void shouldCorsFilterDeactivatedForEmptyAllowedOrigins() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/SpringBootTestClassOrderer.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/SpringBootTestClassOrderer.java | package com.baeldung.jhipster8.config;
import com.baeldung.jhipster8.IntegrationTest;
import java.util.Comparator;
import org.junit.jupiter.api.ClassDescriptor;
import org.junit.jupiter.api.ClassOrderer;
import org.junit.jupiter.api.ClassOrdererContext;
public class SpringBootTestClassOrderer implements ClassOrderer {
@Override
public void orderClasses(ClassOrdererContext context) {
context.getClassDescriptors().sort(Comparator.comparingInt(SpringBootTestClassOrderer::getOrder));
}
private static int getOrder(ClassDescriptor classDescriptor) {
if (classDescriptor.findAnnotation(IntegrationTest.class).isPresent()) {
return 2;
}
return 1;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/timezone/HibernateTimeZoneIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/config/timezone/HibernateTimeZoneIT.java | package com.baeldung.jhipster8.config.timezone;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.repository.timezone.DateTimeWrapper;
import com.baeldung.jhipster8.repository.timezone.DateTimeWrapperRepository;
import java.time.*;
import java.time.format.DateTimeFormatter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for verifying the behavior of Hibernate in the context of storing various date and time types across different databases.
* The tests focus on ensuring that the stored values are correctly transformed and stored according to the configured timezone.
* Timezone is environment specific, and can be adjusted according to your needs.
*
* For more context, refer to:
* - GitHub Issue: https://github.com/jhipster/generator-jhipster/issues/22579
* - Pull Request: https://github.com/jhipster/generator-jhipster/pull/22946
*/
@IntegrationTest
class HibernateTimeZoneIT {
@Autowired
private DateTimeWrapperRepository dateTimeWrapperRepository;
@Autowired
private JdbcTemplate jdbcTemplate;
@Value("${spring.jpa.properties.hibernate.jdbc.time_zone:UTC}")
private String zoneId;
private DateTimeWrapper dateTimeWrapper;
private DateTimeFormatter dateTimeFormatter;
private DateTimeFormatter timeFormatter;
private DateTimeFormatter offsetTimeFormatter;
private DateTimeFormatter dateFormatter;
@BeforeEach
public void setup() {
dateTimeWrapper = new DateTimeWrapper();
dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:10:00.0Z"));
dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:20:00.0"));
dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z"));
dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:40:00.0Z"));
dateTimeWrapper.setLocalTime(LocalTime.parse("14:50:00"));
dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:00:00+02:00"));
dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10"));
dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").withZone(ZoneId.of(zoneId));
timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.of(zoneId));
offsetTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
}
@Test
@Transactional
void storeInstantWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("instant", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant());
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getLocalDateTime().atZone(ZoneId.systemDefault()).format(dateTimeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeOffsetDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getOffsetDateTime().format(dateTimeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeZoneDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getZonedDateTime().format(dateTimeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZoneAccordingToHis1stJan1970Value() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getLocalTime()
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
.atZone(ZoneId.systemDefault())
.format(timeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeOffsetTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZoneAccordingToHis1stJan1970Value() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("offset_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getOffsetTime()
// Convert to configured timezone
.withOffsetSameInstant(ZoneId.of(zoneId).getRules().getOffset(Instant.now()))
// Normalize to System TimeZone.
// TODO this behavior looks a bug, refer to https://github.com/jhipster/generator-jhipster/issues/22579.
.withOffsetSameLocal(OffsetDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault()).getOffset())
// Convert the normalized value to configured timezone
.withOffsetSameInstant(ZoneId.of(zoneId).getRules().getOffset(Instant.EPOCH))
.format(offsetTimeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalDateWithZoneIdConfigShouldBeStoredWithoutTransformation() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_date", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getLocalDate().format(dateFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
private String generateSqlRequest(String fieldName, long id) {
return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id);
}
private void assertThatValueFromSqlRowSetIsEqualToExpectedValue(SqlRowSet sqlRowSet, String expectedValue) {
while (sqlRowSet.next()) {
String dbValue = sqlRowSet.getString(1);
assertThat(dbValue).isNotNull();
assertThat(dbValue).isEqualTo(expectedValue);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/filter/SpaWebFilterIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/filter/SpaWebFilterIT.java | package com.baeldung.jhipster8.web.filter;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.security.AuthoritiesConstants;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
@AutoConfigureMockMvc
@WithMockUser
@IntegrationTest
class SpaWebFilterIT {
@Autowired
private MockMvc mockMvc;
@Test
void testFilterForwardsToIndex() throws Exception {
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void testFilterDoesNotForwardToIndexForApi() throws Exception {
mockMvc.perform(get("/api/authenticate")).andExpect(status().isOk()).andExpect(forwardedUrl(null));
}
@Test
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
void testFilterDoesNotForwardToIndexForV3ApiDocs() throws Exception {
mockMvc.perform(get("/v3/api-docs")).andExpect(status().isOk()).andExpect(forwardedUrl(null));
}
@Test
void testFilterDoesNotForwardToIndexForDotFile() throws Exception {
mockMvc.perform(get("/file.js")).andExpect(status().isNotFound());
}
@Test
void getBackendEndpoint() throws Exception {
mockMvc.perform(get("/test")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void forwardUnmappedFirstLevelMapping() throws Exception {
mockMvc.perform(get("/first-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void forwardUnmappedSecondLevelMapping() throws Exception {
mockMvc.perform(get("/first-level/second-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void forwardUnmappedThirdLevelMapping() throws Exception {
mockMvc.perform(get("/first-level/second-level/third-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void forwardUnmappedDeepMapping() throws Exception {
mockMvc.perform(get("/1/2/3/4/5/6/7/8/9/10")).andExpect(forwardedUrl("/index.html"));
}
@Test
void getUnmappedFirstLevelFile() throws Exception {
mockMvc.perform(get("/foo.js")).andExpect(status().isNotFound());
}
/**
* This test verifies that any files that aren't permitted by Spring Security will be forbidden.
* If you want to change this to return isNotFound(), you need to add a request mapping that
* allows this file in SecurityConfiguration.
*/
@Test
void getUnmappedSecondLevelFile() throws Exception {
mockMvc.perform(get("/foo/bar.js")).andExpect(status().isForbidden());
}
@Test
void getUnmappedThirdLevelFile() throws Exception {
mockMvc.perform(get("/foo/another/bar.js")).andExpect(status().isForbidden());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/TestUtil.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/TestUtil.java | package com.baeldung.jhipster8.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.hamcrest.TypeSafeMatcher;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
/**
* Utility class for testing REST controllers.
*/
public final class TestUtil {
/**
* Create a byte array with a specific size filled with specified data.
*
* @param size the size of the byte array.
* @param data the data to put in the byte array.
* @return the JSON byte array.
*/
public static byte[] createByteArray(int size, String data) {
byte[] byteArray = new byte[size];
for (int i = 0; i < size; i++) {
byteArray[i] = Byte.parseByte(data, 2);
}
return byteArray;
}
/**
* A matcher that tests that the examined string represents the same instant as the reference datetime.
*/
public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {
private final ZonedDateTime date;
public ZonedDateTimeMatcher(ZonedDateTime date) {
this.date = date;
}
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
try {
if (!date.isEqual(ZonedDateTime.parse(item))) {
mismatchDescription.appendText("was ").appendValue(item);
return false;
}
return true;
} catch (DateTimeParseException e) {
mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime");
return false;
}
}
@Override
public void describeTo(Description description) {
description.appendText("a String representing the same Instant as ").appendValue(date);
}
}
/**
* Creates a matcher that matches when the examined string represents the same instant as the reference datetime.
*
* @param date the reference datetime against which the examined string is checked.
*/
public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
return new ZonedDateTimeMatcher(date);
}
/**
* A matcher that tests that the examined number represents the same value - it can be Long, Double, etc - as the reference BigDecimal.
*/
public static class NumberMatcher extends TypeSafeMatcher<Number> {
final BigDecimal value;
public NumberMatcher(BigDecimal value) {
this.value = value;
}
@Override
public void describeTo(Description description) {
description.appendText("a numeric value is ").appendValue(value);
}
@Override
protected boolean matchesSafely(Number item) {
BigDecimal bigDecimal = asDecimal(item);
return bigDecimal != null && value.compareTo(bigDecimal) == 0;
}
private static BigDecimal asDecimal(Number item) {
if (item == null) {
return null;
}
if (item instanceof BigDecimal) {
return (BigDecimal) item;
} else if (item instanceof Long) {
return BigDecimal.valueOf((Long) item);
} else if (item instanceof Integer) {
return BigDecimal.valueOf((Integer) item);
} else if (item instanceof Double) {
return BigDecimal.valueOf((Double) item);
} else if (item instanceof Float) {
return BigDecimal.valueOf((Float) item);
} else {
return BigDecimal.valueOf(item.doubleValue());
}
}
}
/**
* Creates a matcher that matches when the examined number represents the same value as the reference BigDecimal.
*
* @param number the reference BigDecimal against which the examined number is checked.
*/
public static NumberMatcher sameNumber(BigDecimal number) {
return new NumberMatcher(number);
}
/**
* Verifies the equals/hashcode contract on the domain object.
*/
public static <T> void equalsVerifier(Class<T> clazz) throws Exception {
T domainObject1 = clazz.getConstructor().newInstance();
assertThat(domainObject1.toString()).isNotNull();
assertThat(domainObject1).isEqualTo(domainObject1);
assertThat(domainObject1).hasSameHashCodeAs(domainObject1);
// Test with an instance of another class
Object testOtherObject = new Object();
assertThat(domainObject1).isNotEqualTo(testOtherObject);
assertThat(domainObject1).isNotEqualTo(null);
// Test with an instance of the same class
T domainObject2 = clazz.getConstructor().newInstance();
assertThat(domainObject1).isNotEqualTo(domainObject2);
// HashCodes are equals because the objects are not persisted yet
assertThat(domainObject1).hasSameHashCodeAs(domainObject2);
}
/**
* Create a {@link FormattingConversionService} which use ISO date format, instead of the localized one.
* @return the {@link FormattingConversionService}.
*/
public static FormattingConversionService createFormattingConversionService() {
DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService();
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(dfcs);
return dfcs;
}
/**
* Executes a query on the EntityManager finding all stored objects.
* @param <T> The type of objects to be searched
* @param em The instance of the EntityManager
* @param clazz The class type to be searched
* @return A list of all found objects
*/
public static <T> List<T> findAll(EntityManager em, Class<T> clazz) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(clazz);
Root<T> rootEntry = cq.from(clazz);
CriteriaQuery<T> all = cq.select(rootEntry);
TypedQuery<T> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
@SuppressWarnings("unchecked")
public static <T> T createUpdateProxyForBean(T update, T original) {
Enhancer e = new Enhancer();
e.setSuperclass(original.getClass());
e.setCallback(
new MethodInterceptor() {
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
Object val = update.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(update, args);
if (val == null) {
return original.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(original, args);
}
return val;
}
}
);
return (T) e.create();
}
private TestUtil() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/PublicUserResourceIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/PublicUserResourceIT.java | package com.baeldung.jhipster8.web.rest;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.repository.UserRepository;
import com.baeldung.jhipster8.security.AuthoritiesConstants;
import jakarta.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link PublicUserResource} REST controller.
*/
@AutoConfigureMockMvc
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
@IntegrationTest
class PublicUserResourceIT {
private static final String DEFAULT_LOGIN = "johndoe";
@Autowired
private UserRepository userRepository;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restUserMockMvc;
private User user;
@BeforeEach
public void initTest() {
user = UserResourceIT.initTestUser(userRepository, em);
}
@Test
@Transactional
void getAllPublicUsers() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
// Get all the users
restUserMockMvc
.perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
.andExpect(jsonPath("$.[*].email").doesNotExist())
.andExpect(jsonPath("$.[*].imageUrl").doesNotExist())
.andExpect(jsonPath("$.[*].langKey").doesNotExist());
}
@Test
@Transactional
void getAllUsersSortedByParameters() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
restUserMockMvc.perform(get("/api/users?sort=resetKey,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest());
restUserMockMvc.perform(get("/api/users?sort=password,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest());
restUserMockMvc
.perform(get("/api/users?sort=resetKey,desc&sort=id,desc").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
restUserMockMvc.perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/UserResourceIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/UserResourceIT.java | package com.baeldung.jhipster8.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.domain.Authority;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.repository.UserRepository;
import com.baeldung.jhipster8.security.AuthoritiesConstants;
import com.baeldung.jhipster8.service.dto.AdminUserDTO;
import com.baeldung.jhipster8.service.mapper.UserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.EntityManager;
import java.time.Instant;
import java.util.*;
import java.util.function.Consumer;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link UserResource} REST controller.
*/
@AutoConfigureMockMvc
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
@IntegrationTest
class UserResourceIT {
private static final String DEFAULT_LOGIN = "johndoe";
private static final String UPDATED_LOGIN = "jhipster";
private static final Long DEFAULT_ID = 1L;
private static final String DEFAULT_PASSWORD = "passjohndoe";
private static final String UPDATED_PASSWORD = "passjhipster";
private static final String DEFAULT_EMAIL = "johndoe@localhost";
private static final String UPDATED_EMAIL = "jhipster@localhost";
private static final String DEFAULT_FIRSTNAME = "john";
private static final String UPDATED_FIRSTNAME = "jhipsterFirstName";
private static final String DEFAULT_LASTNAME = "doe";
private static final String UPDATED_LASTNAME = "jhipsterLastName";
private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40";
private static final String DEFAULT_LANGKEY = "en";
private static final String UPDATED_LANGKEY = "fr";
@Autowired
private ObjectMapper om;
@Autowired
private UserRepository userRepository;
@Autowired
private UserMapper userMapper;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restUserMockMvc;
private User user;
/**
* Create a User.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which has a required relationship to the User entity.
*/
public static User createEntity(EntityManager em) {
User user = new User();
user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5));
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
return user;
}
/**
* Setups the database with one user.
*/
public static User initTestUser(UserRepository userRepository, EntityManager em) {
userRepository.deleteAll();
User user = createEntity(em);
user.setLogin(DEFAULT_LOGIN);
user.setEmail(DEFAULT_EMAIL);
return user;
}
@BeforeEach
public void initTest() {
user = initTestUser(userRepository, em);
}
@Test
@Transactional
void createUser() throws Exception {
int databaseSizeBeforeCreate = userRepository.findAll().size();
// Create the User
AdminUserDTO user = new AdminUserDTO();
user.setLogin(DEFAULT_LOGIN);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setEmail(DEFAULT_EMAIL);
user.setActivated(true);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc
.perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(user)))
.andExpect(status().isCreated());
// Validate the User in the database
assertPersistedUsers(users -> {
assertThat(users).hasSize(databaseSizeBeforeCreate + 1);
User testUser = users.get(users.size() - 1);
assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
});
}
@Test
@Transactional
void createUserWithExistingId() throws Exception {
int databaseSizeBeforeCreate = userRepository.findAll().size();
AdminUserDTO user = new AdminUserDTO();
user.setId(DEFAULT_ID);
user.setLogin(DEFAULT_LOGIN);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setEmail(DEFAULT_EMAIL);
user.setActivated(true);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// An entity with an existing ID cannot be created, so this API call must fail
restUserMockMvc
.perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(user)))
.andExpect(status().isBadRequest());
// Validate the User in the database
assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
}
@Test
@Transactional
void createUserWithExistingLogin() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeCreate = userRepository.findAll().size();
AdminUserDTO user = new AdminUserDTO();
user.setLogin(DEFAULT_LOGIN); // this login should already be used
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setEmail("anothermail@localhost");
user.setActivated(true);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Create the User
restUserMockMvc
.perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(user)))
.andExpect(status().isBadRequest());
// Validate the User in the database
assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
}
@Test
@Transactional
void createUserWithExistingEmail() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeCreate = userRepository.findAll().size();
AdminUserDTO user = new AdminUserDTO();
user.setLogin("anotherlogin");
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setEmail(DEFAULT_EMAIL); // this email should already be used
user.setActivated(true);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Create the User
restUserMockMvc
.perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(user)))
.andExpect(status().isBadRequest());
// Validate the User in the database
assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
}
@Test
@Transactional
void getAllUsers() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
// Get all the users
restUserMockMvc
.perform(get("/api/admin/users?sort=id,desc").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
.andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME)))
.andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
.andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL)))
.andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY)));
}
@Test
@Transactional
void getUser() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
// Get the user
restUserMockMvc
.perform(get("/api/admin/users/{login}", user.getLogin()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.login").value(user.getLogin()))
.andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME))
.andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL))
.andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL))
.andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY));
}
@Test
@Transactional
void getNonExistingUser() throws Exception {
restUserMockMvc.perform(get("/api/admin/users/unknown")).andExpect(status().isNotFound());
}
@Test
@Transactional
void updateUser() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeUpdate = userRepository.findAll().size();
// Update the user
User updatedUser = userRepository.findById(user.getId()).orElseThrow();
AdminUserDTO user = new AdminUserDTO();
user.setId(updatedUser.getId());
user.setLogin(updatedUser.getLogin());
user.setFirstName(UPDATED_FIRSTNAME);
user.setLastName(UPDATED_LASTNAME);
user.setEmail(UPDATED_EMAIL);
user.setActivated(updatedUser.isActivated());
user.setImageUrl(UPDATED_IMAGEURL);
user.setLangKey(UPDATED_LANGKEY);
user.setCreatedBy(updatedUser.getCreatedBy());
user.setCreatedDate(updatedUser.getCreatedDate());
user.setLastModifiedBy(updatedUser.getLastModifiedBy());
user.setLastModifiedDate(updatedUser.getLastModifiedDate());
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc
.perform(put("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(user)))
.andExpect(status().isOk());
// Validate the User in the database
assertPersistedUsers(users -> {
assertThat(users).hasSize(databaseSizeBeforeUpdate);
User testUser = users.stream().filter(usr -> usr.getId().equals(updatedUser.getId())).findFirst().orElseThrow();
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
});
}
@Test
@Transactional
void updateUserLogin() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeUpdate = userRepository.findAll().size();
// Update the user
User updatedUser = userRepository.findById(user.getId()).orElseThrow();
AdminUserDTO user = new AdminUserDTO();
user.setId(updatedUser.getId());
user.setLogin(UPDATED_LOGIN);
user.setFirstName(UPDATED_FIRSTNAME);
user.setLastName(UPDATED_LASTNAME);
user.setEmail(UPDATED_EMAIL);
user.setActivated(updatedUser.isActivated());
user.setImageUrl(UPDATED_IMAGEURL);
user.setLangKey(UPDATED_LANGKEY);
user.setCreatedBy(updatedUser.getCreatedBy());
user.setCreatedDate(updatedUser.getCreatedDate());
user.setLastModifiedBy(updatedUser.getLastModifiedBy());
user.setLastModifiedDate(updatedUser.getLastModifiedDate());
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc
.perform(put("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(user)))
.andExpect(status().isOk());
// Validate the User in the database
assertPersistedUsers(users -> {
assertThat(users).hasSize(databaseSizeBeforeUpdate);
User testUser = users.stream().filter(usr -> usr.getId().equals(updatedUser.getId())).findFirst().orElseThrow();
assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN);
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
});
}
@Test
@Transactional
void updateUserExistingEmail() throws Exception {
// Initialize the database with 2 users
userRepository.saveAndFlush(user);
User anotherUser = new User();
anotherUser.setLogin("jhipster");
anotherUser.setPassword(RandomStringUtils.randomAlphanumeric(60));
anotherUser.setActivated(true);
anotherUser.setEmail("jhipster@localhost");
anotherUser.setFirstName("java");
anotherUser.setLastName("hipster");
anotherUser.setImageUrl("");
anotherUser.setLangKey("en");
userRepository.saveAndFlush(anotherUser);
// Update the user
User updatedUser = userRepository.findById(user.getId()).orElseThrow();
AdminUserDTO user = new AdminUserDTO();
user.setId(updatedUser.getId());
user.setLogin(updatedUser.getLogin());
user.setFirstName(updatedUser.getFirstName());
user.setLastName(updatedUser.getLastName());
user.setEmail("jhipster@localhost"); // this email should already be used by anotherUser
user.setActivated(updatedUser.isActivated());
user.setImageUrl(updatedUser.getImageUrl());
user.setLangKey(updatedUser.getLangKey());
user.setCreatedBy(updatedUser.getCreatedBy());
user.setCreatedDate(updatedUser.getCreatedDate());
user.setLastModifiedBy(updatedUser.getLastModifiedBy());
user.setLastModifiedDate(updatedUser.getLastModifiedDate());
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc
.perform(put("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(user)))
.andExpect(status().isBadRequest());
}
@Test
@Transactional
void updateUserExistingLogin() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
User anotherUser = new User();
anotherUser.setLogin("jhipster");
anotherUser.setPassword(RandomStringUtils.randomAlphanumeric(60));
anotherUser.setActivated(true);
anotherUser.setEmail("jhipster@localhost");
anotherUser.setFirstName("java");
anotherUser.setLastName("hipster");
anotherUser.setImageUrl("");
anotherUser.setLangKey("en");
userRepository.saveAndFlush(anotherUser);
// Update the user
User updatedUser = userRepository.findById(user.getId()).orElseThrow();
AdminUserDTO user = new AdminUserDTO();
user.setId(updatedUser.getId());
user.setLogin("jhipster"); // this login should already be used by anotherUser
user.setFirstName(updatedUser.getFirstName());
user.setLastName(updatedUser.getLastName());
user.setEmail(updatedUser.getEmail());
user.setActivated(updatedUser.isActivated());
user.setImageUrl(updatedUser.getImageUrl());
user.setLangKey(updatedUser.getLangKey());
user.setCreatedBy(updatedUser.getCreatedBy());
user.setCreatedDate(updatedUser.getCreatedDate());
user.setLastModifiedBy(updatedUser.getLastModifiedBy());
user.setLastModifiedDate(updatedUser.getLastModifiedDate());
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc
.perform(put("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(user)))
.andExpect(status().isBadRequest());
}
@Test
@Transactional
void deleteUser() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeDelete = userRepository.findAll().size();
// Delete the user
restUserMockMvc
.perform(delete("/api/admin/users/{login}", user.getLogin()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database is empty
assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeDelete - 1));
}
@Test
void testUserEquals() throws Exception {
TestUtil.equalsVerifier(User.class);
User user1 = new User();
user1.setId(DEFAULT_ID);
User user2 = new User();
user2.setId(user1.getId());
assertThat(user1).isEqualTo(user2);
user2.setId(2L);
assertThat(user1).isNotEqualTo(user2);
user1.setId(null);
assertThat(user1).isNotEqualTo(user2);
}
@Test
void testUserDTOtoUser() {
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setId(DEFAULT_ID);
userDTO.setLogin(DEFAULT_LOGIN);
userDTO.setFirstName(DEFAULT_FIRSTNAME);
userDTO.setLastName(DEFAULT_LASTNAME);
userDTO.setEmail(DEFAULT_EMAIL);
userDTO.setActivated(true);
userDTO.setImageUrl(DEFAULT_IMAGEURL);
userDTO.setLangKey(DEFAULT_LANGKEY);
userDTO.setCreatedBy(DEFAULT_LOGIN);
userDTO.setLastModifiedBy(DEFAULT_LOGIN);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
User user = userMapper.userDTOToUser(userDTO);
assertThat(user.getId()).isEqualTo(DEFAULT_ID);
assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(user.isActivated()).isTrue();
assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(user.getCreatedBy()).isNull();
assertThat(user.getCreatedDate()).isNotNull();
assertThat(user.getLastModifiedBy()).isNull();
assertThat(user.getLastModifiedDate()).isNotNull();
assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER);
}
@Test
void testUserToUserDTO() {
user.setId(DEFAULT_ID);
user.setCreatedBy(DEFAULT_LOGIN);
user.setCreatedDate(Instant.now());
user.setLastModifiedBy(DEFAULT_LOGIN);
user.setLastModifiedDate(Instant.now());
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.USER);
authorities.add(authority);
user.setAuthorities(authorities);
AdminUserDTO userDTO = userMapper.userToAdminUserDTO(user);
assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID);
assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(userDTO.isActivated()).isTrue();
assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate());
assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate());
assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER);
assertThat(userDTO.toString()).isNotNull();
}
private void assertPersistedUsers(Consumer<List<User>> userAssertion) {
userAssertion.accept(userRepository.findAll());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/AuthorityResourceIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/AuthorityResourceIT.java | package com.baeldung.jhipster8.web.rest;
import static com.baeldung.jhipster8.domain.AuthorityAsserts.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.domain.Authority;
import com.baeldung.jhipster8.repository.AuthorityRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.EntityManager;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link AuthorityResource} REST controller.
*/
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser(authorities = { "ROLE_ADMIN" })
class AuthorityResourceIT {
private static final String ENTITY_API_URL = "/api/authorities";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{name}";
@Autowired
private ObjectMapper om;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restAuthorityMockMvc;
private Authority authority;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Authority createEntity(EntityManager em) {
Authority authority = new Authority().name(UUID.randomUUID().toString());
return authority;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Authority createUpdatedEntity(EntityManager em) {
Authority authority = new Authority().name(UUID.randomUUID().toString());
return authority;
}
@BeforeEach
public void initTest() {
authority = createEntity(em);
}
@Test
@Transactional
void createAuthority() throws Exception {
long databaseSizeBeforeCreate = getRepositoryCount();
// Create the Authority
var returnedAuthority = om.readValue(
restAuthorityMockMvc
.perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(authority)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getContentAsString(),
Authority.class
);
// Validate the Authority in the database
assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
assertAuthorityUpdatableFieldsEquals(returnedAuthority, getPersistedAuthority(returnedAuthority));
}
@Test
@Transactional
void createAuthorityWithExistingId() throws Exception {
// Create the Authority with an existing ID
authorityRepository.saveAndFlush(authority);
long databaseSizeBeforeCreate = getRepositoryCount();
// An entity with an existing ID cannot be created, so this API call must fail
restAuthorityMockMvc
.perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(authority)))
.andExpect(status().isBadRequest());
// Validate the Authority in the database
assertSameRepositoryCount(databaseSizeBeforeCreate);
}
@Test
@Transactional
void getAllAuthorities() throws Exception {
// Initialize the database
authority.setName(UUID.randomUUID().toString());
authorityRepository.saveAndFlush(authority);
// Get all the authorityList
restAuthorityMockMvc
.perform(get(ENTITY_API_URL + "?sort=name,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].name").value(hasItem(authority.getName())));
}
@Test
@Transactional
void getAuthority() throws Exception {
// Initialize the database
authority.setName(UUID.randomUUID().toString());
authorityRepository.saveAndFlush(authority);
// Get the authority
restAuthorityMockMvc
.perform(get(ENTITY_API_URL_ID, authority.getName()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.name").value(authority.getName()));
}
@Test
@Transactional
void getNonExistingAuthority() throws Exception {
// Get the authority
restAuthorityMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
@Transactional
void deleteAuthority() throws Exception {
// Initialize the database
authority.setName(UUID.randomUUID().toString());
authorityRepository.saveAndFlush(authority);
long databaseSizeBeforeDelete = getRepositoryCount();
// Delete the authority
restAuthorityMockMvc
.perform(delete(ENTITY_API_URL_ID, authority.getName()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
}
protected long getRepositoryCount() {
return authorityRepository.count();
}
protected void assertIncrementedRepositoryCount(long countBefore) {
assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
}
protected void assertDecrementedRepositoryCount(long countBefore) {
assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
}
protected void assertSameRepositoryCount(long countBefore) {
assertThat(countBefore).isEqualTo(getRepositoryCount());
}
protected Authority getPersistedAuthority(Authority authority) {
return authorityRepository.findById(authority.getName()).orElseThrow();
}
protected void assertPersistedAuthorityToMatchAllProperties(Authority expectedAuthority) {
assertAuthorityAllPropertiesEquals(expectedAuthority, getPersistedAuthority(expectedAuthority));
}
protected void assertPersistedAuthorityToMatchUpdatableProperties(Authority expectedAuthority) {
assertAuthorityAllUpdatablePropertiesEquals(expectedAuthority, getPersistedAuthority(expectedAuthority));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/AuthenticateControllerIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/AuthenticateControllerIT.java | package com.baeldung.jhipster8.web.rest;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.repository.UserRepository;
import com.baeldung.jhipster8.web.rest.vm.LoginVM;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link AuthenticateController} REST controller.
*/
@AutoConfigureMockMvc
@IntegrationTest
class AuthenticateControllerIT {
@Autowired
private ObjectMapper om;
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private MockMvc mockMvc;
@Test
@Transactional
void testAuthorize() throws Exception {
User user = new User();
user.setLogin("user-jwt-controller");
user.setEmail("user-jwt-controller@example.com");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
userRepository.saveAndFlush(user);
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller");
login.setPassword("test");
mockMvc
.perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty())
.andExpect(header().string("Authorization", not(nullValue())))
.andExpect(header().string("Authorization", not(is(emptyString()))));
}
@Test
@Transactional
void testAuthorizeWithRememberMe() throws Exception {
User user = new User();
user.setLogin("user-jwt-controller-remember-me");
user.setEmail("user-jwt-controller-remember-me@example.com");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
userRepository.saveAndFlush(user);
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller-remember-me");
login.setPassword("test");
login.setRememberMe(true);
mockMvc
.perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty())
.andExpect(header().string("Authorization", not(nullValue())))
.andExpect(header().string("Authorization", not(is(emptyString()))));
}
@Test
void testAuthorizeFails() throws Exception {
LoginVM login = new LoginVM();
login.setUsername("wrong-user");
login.setPassword("wrong password");
mockMvc
.perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(login)))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.id_token").doesNotExist())
.andExpect(header().doesNotExist("Authorization"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/AccountResourceIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/AccountResourceIT.java | package com.baeldung.jhipster8.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.baeldung.jhipster8.IntegrationTest;
import com.baeldung.jhipster8.config.Constants;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.repository.AuthorityRepository;
import com.baeldung.jhipster8.repository.UserRepository;
import com.baeldung.jhipster8.security.AuthoritiesConstants;
import com.baeldung.jhipster8.service.UserService;
import com.baeldung.jhipster8.service.dto.AdminUserDTO;
import com.baeldung.jhipster8.service.dto.PasswordChangeDTO;
import com.baeldung.jhipster8.web.rest.vm.KeyAndPasswordVM;
import com.baeldung.jhipster8.web.rest.vm.ManagedUserVM;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant;
import java.util.*;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link AccountResource} REST controller.
*/
@AutoConfigureMockMvc
@IntegrationTest
class AccountResourceIT {
static final String TEST_USER_LOGIN = "test";
@Autowired
private ObjectMapper om;
@Autowired
private UserRepository userRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private MockMvc restAccountMockMvc;
@Test
@WithUnauthenticatedMockUser
void testNonAuthenticatedUser() throws Exception {
restAccountMockMvc
.perform(get("/api/authenticate").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(""));
}
@Test
@WithMockUser(TEST_USER_LOGIN)
void testAuthenticatedUser() throws Exception {
restAccountMockMvc
.perform(get("/api/authenticate").with(request -> request).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(TEST_USER_LOGIN));
}
@Test
@WithMockUser(TEST_USER_LOGIN)
void testGetExistingAccount() throws Exception {
Set<String> authorities = new HashSet<>();
authorities.add(AuthoritiesConstants.ADMIN);
AdminUserDTO user = new AdminUserDTO();
user.setLogin(TEST_USER_LOGIN);
user.setFirstName("john");
user.setLastName("doe");
user.setEmail("john.doe@jhipster.com");
user.setImageUrl("http://placehold.it/50x50");
user.setLangKey("en");
user.setAuthorities(authorities);
userService.createUser(user);
restAccountMockMvc
.perform(get("/api/account").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.login").value(TEST_USER_LOGIN))
.andExpect(jsonPath("$.firstName").value("john"))
.andExpect(jsonPath("$.lastName").value("doe"))
.andExpect(jsonPath("$.email").value("john.doe@jhipster.com"))
.andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50"))
.andExpect(jsonPath("$.langKey").value("en"))
.andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
@Test
void testGetUnknownAccount() throws Exception {
restAccountMockMvc.perform(get("/api/account").accept(MediaType.APPLICATION_PROBLEM_JSON)).andExpect(status().isUnauthorized());
}
@Test
@Transactional
void testRegisterValid() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("test-register-valid");
validUser.setPassword("password");
validUser.setFirstName("Alice");
validUser.setLastName("Test");
validUser.setEmail("test-register-valid@example.com");
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
assertThat(userRepository.findOneByLogin("test-register-valid")).isEmpty();
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(validUser)))
.andExpect(status().isCreated());
assertThat(userRepository.findOneByLogin("test-register-valid")).isPresent();
}
@Test
@Transactional
void testRegisterInvalidLogin() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("funky-log(n"); // <-- invalid
invalidUser.setPassword("password");
invalidUser.setFirstName("Funky");
invalidUser.setLastName("One");
invalidUser.setEmail("funky@example.com");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com");
assertThat(user).isEmpty();
}
static Stream<ManagedUserVM> invalidUsers() {
return Stream.of(
createInvalidUser("bob", "password", "Bob", "Green", "invalid", true), // <-- invalid
createInvalidUser("bob", "123", "Bob", "Green", "bob@example.com", true), // password with only 3 digits
createInvalidUser("bob", null, "Bob", "Green", "bob@example.com", true) // invalid null password
);
}
@ParameterizedTest
@MethodSource("invalidUsers")
@Transactional
void testRegisterInvalidUsers(ManagedUserVM invalidUser) throws Exception {
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user).isEmpty();
}
private static ManagedUserVM createInvalidUser(
String login,
String password,
String firstName,
String lastName,
String email,
boolean activated
) {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin(login);
invalidUser.setPassword(password);
invalidUser.setFirstName(firstName);
invalidUser.setLastName(lastName);
invalidUser.setEmail(email);
invalidUser.setActivated(activated);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
return invalidUser;
}
@Test
@Transactional
void testRegisterDuplicateLogin() throws Exception {
// First registration
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("alice");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Something");
firstUser.setEmail("alice@example.com");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Duplicate login, different email
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin(firstUser.getLogin());
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail("alice2@example.com");
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setCreatedBy(firstUser.getCreatedBy());
secondUser.setCreatedDate(firstUser.getCreatedDate());
secondUser.setLastModifiedBy(firstUser.getLastModifiedBy());
secondUser.setLastModifiedDate(firstUser.getLastModifiedDate());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// First user
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(firstUser)))
.andExpect(status().isCreated());
// Second (non activated) user
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(secondUser)))
.andExpect(status().isCreated());
Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com");
assertThat(testUser).isPresent();
testUser.orElseThrow().setActivated(true);
userRepository.save(testUser.orElseThrow());
// Second (already activated) user
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
@Transactional
void testRegisterDuplicateEmail() throws Exception {
// First user
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("test-register-duplicate-email");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Test");
firstUser.setEmail("test-register-duplicate-email@example.com");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Register first user
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(firstUser)))
.andExpect(status().isCreated());
Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email");
assertThat(testUser1).isPresent();
// Duplicate email, different login
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin("test-register-duplicate-email-2");
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail(firstUser.getEmail());
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register second (non activated) user
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(secondUser)))
.andExpect(status().isCreated());
Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email");
assertThat(testUser2).isEmpty();
Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2");
assertThat(testUser3).isPresent();
// Duplicate email - with uppercase email address
ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM();
userWithUpperCaseEmail.setId(firstUser.getId());
userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3");
userWithUpperCaseEmail.setPassword(firstUser.getPassword());
userWithUpperCaseEmail.setFirstName(firstUser.getFirstName());
userWithUpperCaseEmail.setLastName(firstUser.getLastName());
userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com");
userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl());
userWithUpperCaseEmail.setLangKey(firstUser.getLangKey());
userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register third (not activated) user
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userWithUpperCaseEmail)))
.andExpect(status().isCreated());
Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3");
assertThat(testUser4).isPresent();
assertThat(testUser4.orElseThrow().getEmail()).isEqualTo("test-register-duplicate-email@example.com");
testUser4.orElseThrow().setActivated(true);
userService.updateUser((new AdminUserDTO(testUser4.orElseThrow())));
// Register 4th (already activated) user
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
@Transactional
void testRegisterAdminIsIgnored() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("badguy");
validUser.setPassword("password");
validUser.setFirstName("Bad");
validUser.setLastName("Guy");
validUser.setEmail("badguy@example.com");
validUser.setActivated(true);
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc
.perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(validUser)))
.andExpect(status().isCreated());
Optional<User> userDup = userRepository.findOneWithAuthoritiesByLogin("badguy");
assertThat(userDup).isPresent();
assertThat(userDup.orElseThrow().getAuthorities())
.hasSize(1)
.containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).orElseThrow());
}
@Test
@Transactional
void testActivateAccount() throws Exception {
final String activationKey = "some activation key";
User user = new User();
user.setLogin("activate-account");
user.setEmail("activate-account@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(false);
user.setActivationKey(activationKey);
userRepository.saveAndFlush(user);
restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)).andExpect(status().isOk());
user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(user.isActivated()).isTrue();
}
@Test
@Transactional
void testActivateAccountWithWrongKey() throws Exception {
restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey")).andExpect(status().isInternalServerError());
}
@Test
@Transactional
@WithMockUser("save-account")
void testSaveAccount() throws Exception {
User user = new User();
user.setLogin("save-account");
user.setEmail("save-account@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-account@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc
.perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneWithAuthoritiesByLogin(user.getLogin()).orElse(null);
assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName());
assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName());
assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail());
assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey());
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl());
assertThat(updatedUser.isActivated()).isTrue();
assertThat(updatedUser.getAuthorities()).isEmpty();
}
@Test
@Transactional
@WithMockUser("save-invalid-email")
void testSaveInvalidEmail() throws Exception {
User user = new User();
user.setLogin("save-invalid-email");
user.setEmail("save-invalid-email@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("invalid email");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc
.perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO)))
.andExpect(status().isBadRequest());
assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
}
@Test
@Transactional
@WithMockUser("save-existing-email")
void testSaveExistingEmail() throws Exception {
User user = new User();
user.setLogin("save-existing-email");
user.setEmail("save-existing-email@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
User anotherUser = new User();
anotherUser.setLogin("save-existing-email2");
anotherUser.setEmail("save-existing-email2@example.com");
anotherUser.setPassword(RandomStringUtils.randomAlphanumeric(60));
anotherUser.setActivated(true);
userRepository.saveAndFlush(anotherUser);
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-existing-email2@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc
.perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com");
}
@Test
@Transactional
@WithMockUser("save-existing-email-and-login")
void testSaveExistingEmailAndLogin() throws Exception {
User user = new User();
user.setLogin("save-existing-email-and-login");
user.setEmail("save-existing-email-and-login@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-existing-email-and-login@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc
.perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com");
}
@Test
@Transactional
@WithMockUser("change-password-wrong-existing-password")
void testChangePasswordWrongExistingPassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-wrong-existing-password");
user.setEmail("change-password-wrong-existing-password@example.com");
userRepository.saveAndFlush(user);
restAccountMockMvc
.perform(
post("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(new PasswordChangeDTO("1" + currentPassword, "new password")))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse();
assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
@WithMockUser("change-password")
void testChangePassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password");
user.setEmail("change-password@example.com");
userRepository.saveAndFlush(user);
restAccountMockMvc
.perform(
post("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, "new password")))
)
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("change-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
@WithMockUser("change-password-too-small")
void testChangePasswordTooSmall() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-small");
user.setEmail("change-password-too-small@example.com");
userRepository.saveAndFlush(user);
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1);
restAccountMockMvc
.perform(
post("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, newPassword)))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
@WithMockUser("change-password-too-long")
void testChangePasswordTooLong() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-long");
user.setEmail("change-password-too-long@example.com");
userRepository.saveAndFlush(user);
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1);
restAccountMockMvc
.perform(
post("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, newPassword)))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
@WithMockUser("change-password-empty")
void testChangePasswordEmpty() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-empty");
user.setEmail("change-password-empty@example.com");
userRepository.saveAndFlush(user);
restAccountMockMvc
.perform(
post("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, "")))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
void testRequestPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("password-reset@example.com");
user.setLangKey("en");
userRepository.saveAndFlush(user);
restAccountMockMvc
.perform(post("/api/account/reset-password/init").content("password-reset@example.com"))
.andExpect(status().isOk());
}
@Test
@Transactional
void testRequestPasswordResetUpperCaseEmail() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setLogin("password-reset-upper-case");
user.setEmail("password-reset-upper-case@example.com");
user.setLangKey("en");
userRepository.saveAndFlush(user);
restAccountMockMvc
.perform(post("/api/account/reset-password/init").content("password-reset-upper-case@EXAMPLE.COM"))
.andExpect(status().isOk());
}
@Test
void testRequestPasswordResetWrongEmail() throws Exception {
restAccountMockMvc
.perform(post("/api/account/reset-password/init").content("password-reset-wrong-email@example.com"))
.andExpect(status().isOk());
}
@Test
@Transactional
void testFinishPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setLogin("finish-password-reset");
user.setEmail("finish-password-reset@example.com");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("new password");
restAccountMockMvc
.perform(
post("/api/account/reset-password/finish")
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(keyAndPassword))
)
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("finish-password-reset-too-small@example.com");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("foo");
restAccountMockMvc
.perform(
post("/api/account/reset-password/finish")
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(keyAndPassword))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
@Test
@Transactional
void testFinishPasswordResetWrongKey() throws Exception {
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey("wrong reset key");
keyAndPassword.setNewPassword("new password");
restAccountMockMvc
.perform(
post("/api/account/reset-password/finish")
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(keyAndPassword))
)
.andExpect(status().isInternalServerError());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/WithUnauthenticatedMockUser.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/WithUnauthenticatedMockUser.java | package com.baeldung.jhipster8.web.rest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithUnauthenticatedMockUser.Factory.class)
public @interface WithUnauthenticatedMockUser {
class Factory implements WithSecurityContextFactory<WithUnauthenticatedMockUser> {
@Override
public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) {
return SecurityContextHolder.createEmptyContext();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/errors/ExceptionTranslatorTestController.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/errors/ExceptionTranslatorTestController.java | package com.baeldung.jhipster8.web.rest.errors;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/exception-translator-test")
public class ExceptionTranslatorTestController {
@GetMapping("/concurrency-failure")
public void concurrencyFailure() {
throw new ConcurrencyFailureException("test concurrency failure");
}
@PostMapping("/method-argument")
public void methodArgument(@Valid @RequestBody TestDTO testDTO) {}
@GetMapping("/missing-servlet-request-part")
public void missingServletRequestPartException(@RequestPart("part") String part) {}
@GetMapping("/missing-servlet-request-parameter")
public void missingServletRequestParameterException(@RequestParam("param") String param) {}
@GetMapping("/access-denied")
public void accessdenied() {
throw new AccessDeniedException("test access denied!");
}
@GetMapping("/unauthorized")
public void unauthorized() {
throw new BadCredentialsException("test authentication failed!");
}
@GetMapping("/response-status")
public void exceptionWithResponseStatus() {
throw new TestResponseStatusException();
}
@GetMapping("/internal-server-error")
public void internalServerError() {
throw new RuntimeException();
}
public static class TestDTO {
@NotNull
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status")
@SuppressWarnings("serial")
public static class TestResponseStatusException extends RuntimeException {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/errors/ExceptionTranslatorIT.java | jhipster-8-modules/jhipster-8-monolithic/src/test/java/com/baeldung/jhipster8/web/rest/errors/ExceptionTranslatorIT.java | package com.baeldung.jhipster8.web.rest.errors;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.baeldung.jhipster8.IntegrationTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
/**
* Integration tests {@link ExceptionTranslator} controller advice.
*/
@WithMockUser
@AutoConfigureMockMvc
@IntegrationTest
class ExceptionTranslatorIT {
@Autowired
private MockMvc mockMvc;
@Test
void testConcurrencyFailure() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/concurrency-failure"))
.andExpect(status().isConflict())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE));
}
@Test
void testMethodArgumentNotValid() throws Exception {
mockMvc
.perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION))
.andExpect(jsonPath("$.fieldErrors.[0].objectName").value("test"))
.andExpect(jsonPath("$.fieldErrors.[0].field").value("test"))
.andExpect(jsonPath("$.fieldErrors.[0].message").value("must not be null"));
}
@Test
void testMissingServletRequestPartException() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/missing-servlet-request-part"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"));
}
@Test
void testMissingServletRequestParameterException() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/missing-servlet-request-parameter"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"));
}
@Test
void testAccessDenied() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/access-denied"))
.andExpect(status().isForbidden())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.403"))
.andExpect(jsonPath("$.detail").value("test access denied!"));
}
@Test
void testUnauthorized() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/unauthorized"))
.andExpect(status().isUnauthorized())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.401"))
.andExpect(jsonPath("$.path").value("/api/exception-translator-test/unauthorized"))
.andExpect(jsonPath("$.detail").value("test authentication failed!"));
}
@Test
void testMethodNotSupported() throws Exception {
mockMvc
.perform(post("/api/exception-translator-test/access-denied"))
.andExpect(status().isMethodNotAllowed())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.405"))
.andExpect(jsonPath("$.detail").value("Request method 'POST' is not supported"));
}
@Test
void testExceptionWithResponseStatus() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/response-status"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"))
.andExpect(jsonPath("$.title").value("test response status"));
}
@Test
void testInternalServerError() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/internal-server-error"))
.andExpect(status().isInternalServerError())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.500"))
.andExpect(jsonPath("$.title").value("Internal Server Error"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/ApplicationWebXml.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/ApplicationWebXml.java | package com.baeldung.jhipster8;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import tech.jhipster.config.DefaultProfileUtil;
/**
* This is a helper Java class that provides an alternative to creating a {@code web.xml}.
* This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc.
*/
public class ApplicationWebXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// set a default to use when no profile is configured.
DefaultProfileUtil.addDefaultProfile(application.application());
return application.sources(Jhipster8MonolithicApp.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/package-info.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/package-info.java | /**
* Application root.
*/
package com.baeldung.jhipster8;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/Jhipster8MonolithicApp.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/Jhipster8MonolithicApp.java | package com.baeldung.jhipster8;
import com.baeldung.jhipster8.config.ApplicationProperties;
import com.baeldung.jhipster8.config.CRLFLogConverter;
import jakarta.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import tech.jhipster.config.DefaultProfileUtil;
import tech.jhipster.config.JHipsterConstants;
@SpringBootApplication
@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class })
public class Jhipster8MonolithicApp {
private static final Logger log = LoggerFactory.getLogger(Jhipster8MonolithicApp.class);
private final Environment env;
public Jhipster8MonolithicApp(Environment env) {
this.env = env;
}
/**
* Initializes jhipster8Monolithic.
* <p>
* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>.
*/
@PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (
activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) &&
activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)
) {
log.error(
"You have misconfigured your application! It should not run " + "with both the 'dev' and 'prod' profiles at the same time."
);
}
if (
activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) &&
activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)
) {
log.error(
"You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time."
);
}
}
/**
* Main method, used to run the application.
*
* @param args the command line arguments.
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Jhipster8MonolithicApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = Optional.ofNullable(env.getProperty("server.ssl.key-store")).map(key -> "https").orElse("http");
String applicationName = env.getProperty("spring.application.name");
String serverPort = env.getProperty("server.port");
String contextPath = Optional.ofNullable(env.getProperty("server.servlet.context-path"))
.filter(StringUtils::isNotBlank)
.orElse("/");
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info(
CRLFLogConverter.CRLF_SAFE_MARKER,
"""
----------------------------------------------------------
\tApplication '{}' is running! Access URLs:
\tLocal: \t\t{}://localhost:{}{}
\tExternal: \t{}://{}:{}{}
\tProfile(s): \t{}
----------------------------------------------------------""",
applicationName,
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles().length == 0 ? env.getDefaultProfiles() : env.getActiveProfiles()
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/GeneratedByJHipster.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/GeneratedByJHipster.java | package com.baeldung.jhipster8;
import jakarta.annotation.Generated;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Generated(value = "JHipster", comments = "Generated by JHipster 8.4.0")
@Retention(RetentionPolicy.SOURCE)
@Target({ ElementType.TYPE })
public @interface GeneratedByJHipster {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/management/package-info.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/management/package-info.java | /**
* Application management.
*/
package com.baeldung.jhipster8.management;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/management/SecurityMetersService.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/management/SecurityMetersService.java | package com.baeldung.jhipster8.management;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;
@Service
public class SecurityMetersService {
public static final String INVALID_TOKENS_METER_NAME = "security.authentication.invalid-tokens";
public static final String INVALID_TOKENS_METER_DESCRIPTION =
"Indicates validation error count of the tokens presented by the clients.";
public static final String INVALID_TOKENS_METER_BASE_UNIT = "errors";
public static final String INVALID_TOKENS_METER_CAUSE_DIMENSION = "cause";
private final Counter tokenInvalidSignatureCounter;
private final Counter tokenExpiredCounter;
private final Counter tokenUnsupportedCounter;
private final Counter tokenMalformedCounter;
public SecurityMetersService(MeterRegistry registry) {
this.tokenInvalidSignatureCounter = invalidTokensCounterForCauseBuilder("invalid-signature").register(registry);
this.tokenExpiredCounter = invalidTokensCounterForCauseBuilder("expired").register(registry);
this.tokenUnsupportedCounter = invalidTokensCounterForCauseBuilder("unsupported").register(registry);
this.tokenMalformedCounter = invalidTokensCounterForCauseBuilder("malformed").register(registry);
}
private Counter.Builder invalidTokensCounterForCauseBuilder(String cause) {
return Counter.builder(INVALID_TOKENS_METER_NAME)
.baseUnit(INVALID_TOKENS_METER_BASE_UNIT)
.description(INVALID_TOKENS_METER_DESCRIPTION)
.tag(INVALID_TOKENS_METER_CAUSE_DIMENSION, cause);
}
public void trackTokenInvalidSignature() {
this.tokenInvalidSignatureCounter.increment();
}
public void trackTokenExpired() {
this.tokenExpiredCounter.increment();
}
public void trackTokenUnsupported() {
this.tokenUnsupportedCounter.increment();
}
public void trackTokenMalformed() {
this.tokenMalformedCounter.increment();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/InvalidPasswordException.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/InvalidPasswordException.java | package com.baeldung.jhipster8.service;
public class InvalidPasswordException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidPasswordException() {
super("Incorrect password");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/UserService.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/UserService.java | package com.baeldung.jhipster8.service;
import com.baeldung.jhipster8.config.Constants;
import com.baeldung.jhipster8.domain.Authority;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.repository.AuthorityRepository;
import com.baeldung.jhipster8.repository.UserRepository;
import com.baeldung.jhipster8.security.AuthoritiesConstants;
import com.baeldung.jhipster8.security.SecurityUtils;
import com.baeldung.jhipster8.service.dto.AdminUserDTO;
import com.baeldung.jhipster8.service.dto.UserDTO;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.jhipster.security.RandomUtil;
/**
* Service class for managing users.
*/
@Service
@Transactional
public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthorityRepository authorityRepository;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authorityRepository = authorityRepository;
}
public Optional<User> activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
return userRepository
.findOneByActivationKey(key)
.map(user -> {
// activate given user for the registration key.
user.setActivated(true);
user.setActivationKey(null);
log.debug("Activated user: {}", user);
return user;
});
}
public Optional<User> completePasswordReset(String newPassword, String key) {
log.debug("Reset user password for reset key {}", key);
return userRepository
.findOneByResetKey(key)
.filter(user -> user.getResetDate().isAfter(Instant.now().minus(1, ChronoUnit.DAYS)))
.map(user -> {
user.setPassword(passwordEncoder.encode(newPassword));
user.setResetKey(null);
user.setResetDate(null);
return user;
});
}
public Optional<User> requestPasswordReset(String mail) {
return userRepository
.findOneByEmailIgnoreCase(mail)
.filter(User::isActivated)
.map(user -> {
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
return user;
});
}
public User registerUser(AdminUserDTO userDTO, String password) {
userRepository
.findOneByLogin(userDTO.getLogin().toLowerCase())
.ifPresent(existingUser -> {
boolean removed = removeNonActivatedUser(existingUser);
if (!removed) {
throw new UsernameAlreadyUsedException();
}
});
userRepository
.findOneByEmailIgnoreCase(userDTO.getEmail())
.ifPresent(existingUser -> {
boolean removed = removeNonActivatedUser(existingUser);
if (!removed) {
throw new EmailAlreadyUsedException();
}
});
User newUser = new User();
String encryptedPassword = passwordEncoder.encode(password);
newUser.setLogin(userDTO.getLogin().toLowerCase());
// new user gets initially a generated password
newUser.setPassword(encryptedPassword);
newUser.setFirstName(userDTO.getFirstName());
newUser.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
newUser.setEmail(userDTO.getEmail().toLowerCase());
}
newUser.setImageUrl(userDTO.getImageUrl());
newUser.setLangKey(userDTO.getLangKey());
// new user is not active
newUser.setActivated(false);
// new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey());
Set<Authority> authorities = new HashSet<>();
authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add);
newUser.setAuthorities(authorities);
userRepository.save(newUser);
log.debug("Created Information for User: {}", newUser);
return newUser;
}
private boolean removeNonActivatedUser(User existingUser) {
if (existingUser.isActivated()) {
return false;
}
userRepository.delete(existingUser);
userRepository.flush();
return true;
}
public User createUser(AdminUserDTO userDTO) {
User user = new User();
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
user.setEmail(userDTO.getEmail().toLowerCase());
}
user.setImageUrl(userDTO.getImageUrl());
if (userDTO.getLangKey() == null) {
user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language
} else {
user.setLangKey(userDTO.getLangKey());
}
String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
user.setPassword(encryptedPassword);
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
user.setActivated(true);
if (userDTO.getAuthorities() != null) {
Set<Authority> authorities = userDTO
.getAuthorities()
.stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
user.setAuthorities(authorities);
}
userRepository.save(user);
log.debug("Created Information for User: {}", user);
return user;
}
/**
* Update all information for a specific user, and return the modified user.
*
* @param userDTO user to update.
* @return updated user.
*/
public Optional<AdminUserDTO> updateUser(AdminUserDTO userDTO) {
return Optional.of(userRepository.findById(userDTO.getId()))
.filter(Optional::isPresent)
.map(Optional::get)
.map(user -> {
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
user.setEmail(userDTO.getEmail().toLowerCase());
}
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> managedAuthorities = user.getAuthorities();
managedAuthorities.clear();
userDTO
.getAuthorities()
.stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(managedAuthorities::add);
userRepository.save(user);
log.debug("Changed Information for User: {}", user);
return user;
})
.map(AdminUserDTO::new);
}
public void deleteUser(String login) {
userRepository
.findOneByLogin(login)
.ifPresent(user -> {
userRepository.delete(user);
log.debug("Deleted User: {}", user);
});
}
/**
* Update basic information (first name, last name, email, language) for the current user.
*
* @param firstName first name of user.
* @param lastName last name of user.
* @param email email id of user.
* @param langKey language key.
* @param imageUrl image URL of user.
*/
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
if (email != null) {
user.setEmail(email.toLowerCase());
}
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
userRepository.save(user);
log.debug("Changed Information for User: {}", user);
});
}
@Transactional
public void changePassword(String currentClearTextPassword, String newPassword) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
String currentEncryptedPassword = user.getPassword();
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
throw new InvalidPasswordException();
}
String encryptedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encryptedPassword);
log.debug("Changed password for User: {}", user);
});
}
@Transactional(readOnly = true)
public Page<AdminUserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAll(pageable).map(AdminUserDTO::new);
}
@Transactional(readOnly = true)
public Page<UserDTO> getAllPublicUsers(Pageable pageable) {
return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
.forEach(user -> {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
});
}
/**
* Gets a list of all the authorities.
* @return a list of all the authorities.
*/
@Transactional(readOnly = true)
public List<String> getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).toList();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/UsernameAlreadyUsedException.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/UsernameAlreadyUsedException.java | package com.baeldung.jhipster8.service;
public class UsernameAlreadyUsedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UsernameAlreadyUsedException() {
super("Login name already used!");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/package-info.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/package-info.java | /**
* Service layer.
*/
package com.baeldung.jhipster8.service;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/MailService.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/MailService.java | package com.baeldung.jhipster8.service;
import com.baeldung.jhipster8.domain.User;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringTemplateEngine;
import tech.jhipster.config.JHipsterProperties;
/**
* Service for sending emails asynchronously.
* <p>
* We use the {@link Async} annotation to send emails asynchronously.
*/
@Service
public class MailService {
private final Logger log = LoggerFactory.getLogger(MailService.class);
private static final String USER = "user";
private static final String BASE_URL = "baseUrl";
private final JHipsterProperties jHipsterProperties;
private final JavaMailSender javaMailSender;
private final MessageSource messageSource;
private final SpringTemplateEngine templateEngine;
public MailService(
JHipsterProperties jHipsterProperties,
JavaMailSender javaMailSender,
MessageSource messageSource,
SpringTemplateEngine templateEngine
) {
this.jHipsterProperties = jHipsterProperties;
this.javaMailSender = javaMailSender;
this.messageSource = messageSource;
this.templateEngine = templateEngine;
}
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
this.sendEmailSync(to, subject, content, isMultipart, isHtml);
}
private void sendEmailSync(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug(
"Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart,
isHtml,
to,
subject,
content
);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (MailException | MessagingException e) {
log.warn("Email could not be sent to user '{}'", to, e);
}
}
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
this.sendEmailFromTemplateSync(user, templateName, titleKey);
}
private void sendEmailFromTemplateSync(User user, String templateName, String titleKey) {
if (user.getEmail() == null) {
log.debug("Email doesn't exist for user '{}'", user.getLogin());
return;
}
Locale locale = Locale.forLanguageTag(user.getLangKey());
Context context = new Context(locale);
context.setVariable(USER, user);
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
String content = templateEngine.process(templateName, context);
String subject = messageSource.getMessage(titleKey, null, locale);
this.sendEmailSync(user.getEmail(), subject, content, false, true);
}
@Async
public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail());
this.sendEmailFromTemplateSync(user, "mail/activationEmail", "email.activation.title");
}
@Async
public void sendCreationEmail(User user) {
log.debug("Sending creation email to '{}'", user.getEmail());
this.sendEmailFromTemplateSync(user, "mail/creationEmail", "email.activation.title");
}
@Async
public void sendPasswordResetMail(User user) {
log.debug("Sending password reset email to '{}'", user.getEmail());
this.sendEmailFromTemplateSync(user, "mail/passwordResetEmail", "email.reset.title");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/EmailAlreadyUsedException.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/EmailAlreadyUsedException.java | package com.baeldung.jhipster8.service;
public class EmailAlreadyUsedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EmailAlreadyUsedException() {
super("Email is already in use!");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/dto/package-info.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/dto/package-info.java | /**
* Data transfer objects for rest mapping.
*/
package com.baeldung.jhipster8.service.dto;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/dto/PasswordChangeDTO.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/dto/PasswordChangeDTO.java | package com.baeldung.jhipster8.service.dto;
import java.io.Serializable;
/**
* A DTO representing a password change required data - current and new password.
*/
public class PasswordChangeDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String currentPassword;
private String newPassword;
public PasswordChangeDTO() {
// Empty constructor needed for Jackson.
}
public PasswordChangeDTO(String currentPassword, String newPassword) {
this.currentPassword = currentPassword;
this.newPassword = newPassword;
}
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/dto/UserDTO.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/dto/UserDTO.java | package com.baeldung.jhipster8.service.dto;
import com.baeldung.jhipster8.domain.User;
import java.io.Serializable;
/**
* A DTO representing a user, with only the public attributes.
*/
public class UserDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String login;
public UserDTO() {
// Empty constructor needed for Jackson.
}
public UserDTO(User user) {
this.id = user.getId();
// Customize it here if you need, or not, firstName/lastName/etc
this.login = user.getLogin();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
// prettier-ignore
@Override
public String toString() {
return "UserDTO{" +
"id='" + id + '\'' +
", login='" + login + '\'' +
"}";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/dto/AdminUserDTO.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/dto/AdminUserDTO.java | package com.baeldung.jhipster8.service.dto;
import com.baeldung.jhipster8.config.Constants;
import com.baeldung.jhipster8.domain.Authority;
import com.baeldung.jhipster8.domain.User;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.time.Instant;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A DTO representing a user, with his authorities.
*/
public class AdminUserDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
@NotBlank
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
private String login;
@Size(max = 50)
private String firstName;
@Size(max = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
private String email;
@Size(max = 256)
private String imageUrl;
private boolean activated = false;
@Size(min = 2, max = 10)
private String langKey;
private String createdBy;
private Instant createdDate;
private String lastModifiedBy;
private Instant lastModifiedDate;
private Set<String> authorities;
public AdminUserDTO() {
// Empty constructor needed for Jackson.
}
public AdminUserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email = user.getEmail();
this.activated = user.isActivated();
this.imageUrl = user.getImageUrl();
this.langKey = user.getLangKey();
this.createdBy = user.getCreatedBy();
this.createdDate = user.getCreatedDate();
this.lastModifiedBy = user.getLastModifiedBy();
this.lastModifiedDate = user.getLastModifiedDate();
this.authorities = user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toSet());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Set<String> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<String> authorities) {
this.authorities = authorities;
}
// prettier-ignore
@Override
public String toString() {
return "AdminUserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/mapper/package-info.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/mapper/package-info.java | /**
* Data transfer objects mappers.
*/
package com.baeldung.jhipster8.service.mapper;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/mapper/UserMapper.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/mapper/UserMapper.java | package com.baeldung.jhipster8.service.mapper;
import com.baeldung.jhipster8.domain.Authority;
import com.baeldung.jhipster8.domain.User;
import com.baeldung.jhipster8.service.dto.AdminUserDTO;
import com.baeldung.jhipster8.service.dto.UserDTO;
import java.util.*;
import java.util.stream.Collectors;
import org.mapstruct.BeanMapping;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.springframework.stereotype.Service;
/**
* Mapper for the entity {@link User} and its DTO called {@link UserDTO}.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
* support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class UserMapper {
public List<UserDTO> usersToUserDTOs(List<User> users) {
return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).toList();
}
public UserDTO userToUserDTO(User user) {
return new UserDTO(user);
}
public List<AdminUserDTO> usersToAdminUserDTOs(List<User> users) {
return users.stream().filter(Objects::nonNull).map(this::userToAdminUserDTO).toList();
}
public AdminUserDTO userToAdminUserDTO(User user) {
return new AdminUserDTO(user);
}
public List<User> userDTOsToUsers(List<AdminUserDTO> userDTOs) {
return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).toList();
}
public User userDTOToUser(AdminUserDTO userDTO) {
if (userDTO == null) {
return null;
} else {
User user = new User();
user.setId(userDTO.getId());
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
user.setAuthorities(authorities);
return user;
}
}
private Set<Authority> authoritiesFromStrings(Set<String> authoritiesAsString) {
Set<Authority> authorities = new HashSet<>();
if (authoritiesAsString != null) {
authorities = authoritiesAsString
.stream()
.map(string -> {
Authority auth = new Authority();
auth.setName(string);
return auth;
})
.collect(Collectors.toSet());
}
return authorities;
}
public User userFromId(Long id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
@Named("id")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
public UserDTO toDtoId(User user) {
if (user == null) {
return null;
}
UserDTO userDto = new UserDTO();
userDto.setId(user.getId());
return userDto;
}
@Named("idSet")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
public Set<UserDTO> toDtoIdSet(Set<User> users) {
if (users == null) {
return Collections.emptySet();
}
Set<UserDTO> userSet = new HashSet<>();
for (User userEntity : users) {
userSet.add(this.toDtoId(userEntity));
}
return userSet;
}
@Named("login")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
@Mapping(target = "login", source = "login")
public UserDTO toDtoLogin(User user) {
if (user == null) {
return null;
}
UserDTO userDto = new UserDTO();
userDto.setId(user.getId());
userDto.setLogin(user.getLogin());
return userDto;
}
@Named("loginSet")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
@Mapping(target = "login", source = "login")
public Set<UserDTO> toDtoLoginSet(Set<User> users) {
if (users == null) {
return Collections.emptySet();
}
Set<UserDTO> userSet = new HashSet<>();
for (User userEntity : users) {
userSet.add(this.toDtoLogin(userEntity));
}
return userSet;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/aop/logging/package-info.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/aop/logging/package-info.java | /**
* Logging aspect.
*/
package com.baeldung.jhipster8.aop.logging;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/aop/logging/LoggingAspect.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/aop/logging/LoggingAspect.java | package com.baeldung.jhipster8.aop.logging;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import tech.jhipster.config.JHipsterConstants;
/**
* Aspect for logging execution of service and repository Spring components.
*
* By default, it only runs with the "dev" profile.
*/
@Aspect
public class LoggingAspect {
private final Environment env;
public LoggingAspect(Environment env) {
this.env = env;
}
/**
* Pointcut that matches all repositories, services and Web REST endpoints.
*/
@Pointcut(
"within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)"
)
public void springBeanPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Pointcut that matches all Spring beans in the application's main packages.
*/
@Pointcut(
"within(com.baeldung.jhipster8.repository..*)" +
" || within(com.baeldung.jhipster8.service..*)" +
" || within(com.baeldung.jhipster8.web.rest..*)"
)
public void applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Retrieves the {@link Logger} associated to the given {@link JoinPoint}.
*
* @param joinPoint join point we want the logger for.
* @return {@link Logger} associated to the given {@link JoinPoint}.
*/
private Logger logger(JoinPoint joinPoint) {
return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
logger(joinPoint).error(
"Exception in {}() with cause = '{}' and exception = '{}'",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL",
e.getMessage(),
e
);
} else {
logger(joinPoint).error(
"Exception in {}() with cause = {}",
joinPoint.getSignature().getName(),
e.getCause() != null ? String.valueOf(e.getCause()) : "NULL"
);
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice.
* @return result.
* @throws Throwable throws {@link IllegalArgumentException}.
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Logger log = logger(joinPoint);
if (log.isDebugEnabled()) {
log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName());
throw e;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/domain/package-info.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/domain/package-info.java | /**
* Domain objects.
*/
package com.baeldung.jhipster8.domain;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/domain/Authority.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/domain/Authority.java | package com.baeldung.jhipster8.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import org.springframework.data.domain.Persistable;
/**
* A Authority.
*/
@Entity
@Table(name = "jhi_authority")
@JsonIgnoreProperties(value = { "new", "id" })
@SuppressWarnings("common-java:DuplicatedBlocks")
public class Authority implements Serializable, Persistable<String> {
private static final long serialVersionUID = 1L;
@NotNull
@Size(max = 50)
@Id
@Column(name = "name", length = 50, nullable = false)
private String name;
@Transient
private boolean isPersisted;
// jhipster-needle-entity-add-field - JHipster will add fields here
public String getName() {
return this.name;
}
public Authority name(String name) {
this.setName(name);
return this;
}
public void setName(String name) {
this.name = name;
}
@PostLoad
@PostPersist
public void updateEntityState() {
this.setIsPersisted();
}
@Override
public String getId() {
return this.name;
}
@Transient
@Override
public boolean isNew() {
return !this.isPersisted;
}
public Authority setIsPersisted() {
this.isPersisted = true;
return this;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Authority)) {
return false;
}
return getName() != null && getName().equals(((Authority) o).getName());
}
@Override
public int hashCode() {
return Objects.hashCode(getName());
}
// prettier-ignore
@Override
public String toString() {
return "Authority{" +
"name=" + getName() +
"}";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/domain/User.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/domain/User.java | package com.baeldung.jhipster8.domain;
import com.baeldung.jhipster8.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.BatchSize;
/**
* A user.
*/
@Entity
@Table(name = "jhi_user")
public class User extends AbstractAuditingEntity<Long> implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash", length = 60, nullable = false)
private String password;
@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;
@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
@Column(length = 254, unique = true)
private String email;
@NotNull
@Column(nullable = false)
private boolean activated = false;
@Size(min = 2, max = 10)
@Column(name = "lang_key", length = 10)
private String langKey;
@Size(max = 256)
@Column(name = "image_url", length = 256)
private String imageUrl;
@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
private String activationKey;
@Size(max = 20)
@Column(name = "reset_key", length = 20)
@JsonIgnore
private String resetKey;
@Column(name = "reset_date")
private Instant resetDate = null;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") },
inverseJoinColumns = { @JoinColumn(name = "authority_name", referencedColumnName = "name") }
)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/domain/AbstractAuditingEntity.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/domain/AbstractAuditingEntity.java | package com.baeldung.jhipster8.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import java.io.Serializable;
import java.time.Instant;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
/**
* Base abstract class for entities which will hold definitions for created, last modified, created by,
* last modified by attributes.
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate" }, allowGetters = true)
public abstract class AbstractAuditingEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
public abstract T getId();
@CreatedBy
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
private String createdBy;
@CreatedDate
@Column(name = "created_date", updatable = false)
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
private Instant lastModifiedDate = Instant.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/repository/UserRepository.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/repository/UserRepository.java | package com.baeldung.jhipster8.repository;
import com.baeldung.jhipster8.domain.User;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the {@link User} entity.
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime);
Optional<User> findOneByResetKey(String resetKey);
Optional<User> findOneByEmailIgnoreCase(String email);
Optional<User> findOneByLogin(String login);
@EntityGraph(attributePaths = "authorities")
Optional<User> findOneWithAuthoritiesByLogin(String login);
@EntityGraph(attributePaths = "authorities")
Optional<User> findOneWithAuthoritiesByEmailIgnoreCase(String email);
Page<User> findAllByIdNotNullAndActivatedIsTrue(Pageable pageable);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/repository/package-info.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/repository/package-info.java | /**
* Repository layer.
*/
package com.baeldung.jhipster8.repository;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/repository/AuthorityRepository.java | jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/repository/AuthorityRepository.java | package com.baeldung.jhipster8.repository;
import com.baeldung.jhipster8.domain.Authority;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the Authority entity.
*/
@SuppressWarnings("unused")
@Repository
public interface AuthorityRepository extends JpaRepository<Authority, String> {}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.