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/web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/FormServlet.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/FormServlet.java
package com.baeldung.servlets; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "FormServlet", urlPatterns = "/calculateServlet") public class FormServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String height = request.getParameter("height"); String weight = request.getParameter("weight"); try { double bmi = calculateBMI(Double.parseDouble(weight), Double.parseDouble(height)); request.setAttribute("bmi", bmi); response.setHeader("Test", "Success"); response.setHeader("BMI", String.valueOf(bmi)); request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response); } catch (Exception e) { request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/index.jsp"); dispatcher.forward(request, response); } private Double calculateBMI(Double weight, Double height) { return weight / (height * height); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/UserLoginServlet.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/UserLoginServlet.java
package com.baeldung.servlets; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; @WebServlet("/u_login") public class UserLoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.setAttribute("userId", request.getParameter("userId")); request.setAttribute("id", session.getAttribute("userId")); request.getRequestDispatcher("/WEB-INF/jsp/userlogin.jsp").forward(request, response); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/MainServlet.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/MainServlet.java
package com.baeldung.servlets; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet("/main") public class MainServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/LoginServlet.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/LoginServlet.java
package com.baeldung.servlets; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.*; import java.io.IOException; import java.util.Optional; /** * Created by adam. */ @WebServlet(name = "LoginServlet", urlPatterns = "/login") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CookieReader cookieReader = new CookieReader(request); Optional<String> uiColor = cookieReader.readCookie("uiColor"); Optional<String> userName = cookieReader.readCookie("userName"); request.setAttribute("uiColor", uiColor.orElse("blue")); if (!userName.isPresent()) { RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/login.jsp"); dispatcher.forward(request, response); } else { response.sendRedirect("/welcome"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpSession session = request.getSession(); session.setAttribute("sampleKey", "Sample Value"); String uiColor = request.getParameter("color"); String userName = request.getParameter("name"); Cookie uiColorCookie = new Cookie("uiColor", uiColor); response.addCookie(uiColorCookie); Cookie userNameCookie = new Cookie("userName", userName); response.addCookie(userNameCookie); response.sendRedirect("/welcome"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/WelcomeServlet.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/WelcomeServlet.java
package com.baeldung.servlets; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Optional; /** * Created by adam. */ @WebServlet(name = "WelcomeServlet", urlPatterns = "/welcome") public class WelcomeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CookieReader cookieReader = new CookieReader(request); Optional<String> uiColor = cookieReader.readCookie("uiColor"); Optional<String> userName = cookieReader.readCookie("userName"); if (!userName.isPresent()) { response.sendRedirect("/login"); } else { request.setAttribute("uiColor", uiColor.orElse("blue")); request.setAttribute("userName", userName.get()); request.setAttribute("sessionAttribute", request.getSession() .getAttribute("sampleKey")); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/welcome.jsp"); dispatcher.forward(request, response); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { Cookie userNameCookieRemove = new Cookie("userName", ""); userNameCookieRemove.setMaxAge(0); response.addCookie(userNameCookieRemove); response.sendRedirect("/login"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/CookieReader.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/CookieReader.java
package com.baeldung.servlets; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.Optional; /** * Created by adam. * * Class which simplifies reading cookies from request. */ public class CookieReader { private HttpServletRequest request; /** * The constructor. * * @param request request from which cookies will be read */ public CookieReader(HttpServletRequest request) { this.request = request; } /** * Reads cookie by key from request. * * @param key the key of a cookie * @return returns cookie value */ public Optional<String> readCookie(String key) { return Arrays.stream(request.getCookies()) .filter(c -> key.equals(c.getName())) .map(Cookie::getValue) .findAny(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/mock/UserServlet.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/servlets/mock/UserServlet.java
package com.baeldung.servlets.mock; import java.io.IOException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet(name = "UserServlet", urlPatterns = "/user") public class UserServlet extends HttpServlet { private static final long serialVersionUID = 2923732283720972121L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); response.getWriter() .append("Full Name: " + firstName + " " + lastName); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/setparam/SanitizeParametersRequestWrapper.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/setparam/SanitizeParametersRequestWrapper.java
package com.baeldung.setparam; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.apache.commons.text.StringEscapeUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; public class SanitizeParametersRequestWrapper extends HttpServletRequestWrapper { private final Map<String, String[]> sanitizedMap; public SanitizeParametersRequestWrapper(HttpServletRequest request) { super(request); sanitizedMap = Collections.unmodifiableMap( request.getParameterMap().entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> Arrays.stream(entry.getValue()) .map(StringEscapeUtils::escapeHtml4) .toArray(String[]::new) ))); } @Override public Map<String, String[]> getParameterMap() { return sanitizedMap; } @Override public String[] getParameterValues(String name) { return Optional.ofNullable(getParameterMap().get(name)) .map(values -> Arrays.copyOf(values, values.length)) .orElse(null); } @Override public String getParameter(String name) { return Optional.ofNullable(getParameterValues(name)) .map(values -> values[0]) .orElse(null); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/setparam/SanitizeParametersFilter.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/setparam/SanitizeParametersFilter.java
package com.baeldung.setparam; import java.io.IOException; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.http.HttpServletRequest; @WebFilter(urlPatterns = { "/setparam/with-sanitize.jsp" }) public class SanitizeParametersFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; chain.doFilter(new SanitizeParametersRequestWrapper(httpReq), response); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/setparam/SetParameterRequestWrapper.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/setparam/SetParameterRequestWrapper.java
package com.baeldung.setparam; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; public class SetParameterRequestWrapper extends HttpServletRequestWrapper { private final Map<String, String[]> paramMap; public SetParameterRequestWrapper(HttpServletRequest request) { super(request); paramMap = new HashMap<>(request.getParameterMap()); } @Override public Map<String, String[]> getParameterMap() { return Collections.unmodifiableMap(paramMap); } @Override public String[] getParameterValues(String name) { return Optional.ofNullable(getParameterMap().get(name)) .map(values -> Arrays.copyOf(values, values.length)) .orElse(null); } @Override public String getParameter(String name) { return Optional.ofNullable(getParameterValues(name)) .map(values -> values[0]) .orElse(null); } public void setParameter(String name, String value) { paramMap.put(name, new String[] {value}); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/setparam/LanguageServlet.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/setparam/LanguageServlet.java
package com.baeldung.setparam; import java.io.IOException; import java.util.Locale; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet(name = "LanguageServlet", urlPatterns = "/setparam/lang") public class LanguageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { SetParameterRequestWrapper requestWrapper = new SetParameterRequestWrapper(request); requestWrapper.setParameter("locale", Locale.getDefault().getLanguage()); request.getRequestDispatcher("/setparam/3rd_party_module.jsp").forward(requestWrapper, response); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/clientinfo/AccountServlet.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/clientinfo/AccountServlet.java
package com.baeldung.clientinfo; import java.io.IOException; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet(name = "AccountServlet", urlPatterns = "/account") public class AccountServlet extends HttpServlet { public static final Logger log = LoggerFactory.getLogger(AccountServlet.class); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { AccountLogic accountLogic = new AccountLogic(); Map<String, String> clientInfo = accountLogic.getClientInfo(request); log.info("Request client info: {}, " + clientInfo); response.setStatus(HttpServletResponse.SC_OK); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jakarta-servlets/src/main/java/com/baeldung/clientinfo/AccountLogic.java
web-modules/jakarta-servlets/src/main/java/com/baeldung/clientinfo/AccountLogic.java
package com.baeldung.clientinfo; import java.util.HashMap; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import ua_parser.Client; import ua_parser.Parser; public class AccountLogic { public Map<String, String> getClientInfo(HttpServletRequest request) { String remoteAddr = request.getRemoteAddr(); String remoteHost = request.getRemoteHost(); String remoteUser = request.getRemoteUser(); String contentType = request.getHeader("content-type"); String userAgent = request.getHeader("user-agent"); Parser uaParser = new Parser(); Client client = uaParser.parse(userAgent); Map<String, String> clientInfo = new HashMap<>(); clientInfo.put("os_family", client.os.family); clientInfo.put("device_family", client.device.family); clientInfo.put("userAgent_family", client.userAgent.family); clientInfo.put("remote_address", remoteAddr); clientInfo.put("remote_host", remoteHost); clientInfo.put("remote_user", remoteUser); clientInfo.put("content_type", contentType); return clientInfo; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/google-web-toolkit/src/main/java/com/baeldung/server/MessageServiceImpl.java
web-modules/google-web-toolkit/src/main/java/com/baeldung/server/MessageServiceImpl.java
package com.baeldung.server; import com.baeldung.shared.MessageService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import java.time.LocalDateTime; /** * The server-side implementation of the RPC service. */ @SuppressWarnings("serial") public class MessageServiceImpl extends RemoteServiceServlet implements MessageService { public String sendMessage(String message) throws IllegalArgumentException { if (message == null) { throw new IllegalArgumentException("message is null"); } return "Hello, " + message + "!<br><br> Time received: " + LocalDateTime.now(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/google-web-toolkit/src/main/java/com/baeldung/client/Google_web_toolkit.java
web-modules/google-web-toolkit/src/main/java/com/baeldung/client/Google_web_toolkit.java
package com.baeldung.client; import com.baeldung.shared.MessageService; import com.baeldung.shared.MessageServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class Google_web_toolkit implements EntryPoint { private final MessageServiceAsync messageServiceAsync = GWT.create(MessageService.class); public void onModuleLoad() { Button sendButton = new Button("Submit"); TextBox nameField = new TextBox(); nameField.setText("Hi there"); Label warningLabel = new Label(); sendButton.addStyleName("sendButton"); RootPanel.get("nameFieldContainer").add(nameField); RootPanel.get("sendButtonContainer").add(sendButton); RootPanel.get("errorLabelContainer").add(warningLabel); Button closeButton = new Button("Thanks"); closeButton.getElement().setId("closeButton"); Label textToServerLabel = new Label(); HTML serverResponseLabel = new HTML(); VerticalPanel vPanel = new VerticalPanel(); vPanel.addStyleName("vPanel"); vPanel.add(new HTML("Sending message to the server:")); vPanel.add(textToServerLabel); vPanel.add(new HTML("<br><b>Server replies:</b>")); vPanel.add(serverResponseLabel); vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT); vPanel.add(closeButton); vPanel.setVisible(false); RootPanel.get("serverResponseContainer").add(vPanel); closeButton.addClickHandler(event -> { sendButton.setEnabled(true); sendButton.setFocus(true); vPanel.setVisible(false); }); class MyHandler implements ClickHandler, KeyUpHandler { public void onClick(ClickEvent event) { sendMessageToServer(); } public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendMessageToServer(); } } private void sendMessageToServer() { warningLabel.setText(""); String textToServer = nameField.getText(); if (textToServer == null || textToServer.isEmpty()) { warningLabel.setText("Please enter the message"); return; } sendButton.setEnabled(false); textToServerLabel.setText(textToServer); serverResponseLabel.setText(""); messageServiceAsync.sendMessage(textToServer, new AsyncCallback<String>() { public void onFailure(Throwable caught) { serverResponseLabel.addStyleName("serverResponseLabelError"); serverResponseLabel.setHTML("server error occurred"); closeButton.setFocus(true); } public void onSuccess(String result) { serverResponseLabel.removeStyleName("serverResponseLabelError"); serverResponseLabel.setHTML(result); closeButton.setFocus(true); vPanel.setVisible(true); } }); } } // Add a handler to send the name to the server MyHandler handler = new MyHandler(); sendButton.addClickHandler(handler); nameField.addKeyUpHandler(handler); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/google-web-toolkit/src/main/java/com/baeldung/shared/MessageServiceAsync.java
web-modules/google-web-toolkit/src/main/java/com/baeldung/shared/MessageServiceAsync.java
package com.baeldung.shared; import com.google.gwt.user.client.rpc.AsyncCallback; /** * The async counterpart of <code>MessageService</code>. */ public interface MessageServiceAsync { void sendMessage(String input, AsyncCallback<String> callback) throws IllegalArgumentException; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/google-web-toolkit/src/main/java/com/baeldung/shared/MessageService.java
web-modules/google-web-toolkit/src/main/java/com/baeldung/shared/MessageService.java
package com.baeldung.shared; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * The client-side stub for the RPC service. */ @RemoteServiceRelativePath("greet") public interface MessageService extends RemoteService { String sendMessage(String message) throws IllegalArgumentException; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java
web-modules/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java
package com.baeldung.server; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import javax.naming.NamingException; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriBuilder; import org.apache.commons.io.IOUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine; import org.junit.Before; import org.junit.Test; import com.baeldung.client.ServicesInterface; import com.baeldung.model.Movie; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class RestEasyClientLiveTest { public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/resteasy/rest"); Movie transformerMovie = null; Movie batmanMovie = null; ObjectMapper jsonMapper = null; @Before public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException { jsonMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); jsonMapper.setDateFormat(sdf); try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/transformer.json")) { final String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); } catch (final Exception e) { e.printStackTrace(); throw new RuntimeException("Test is going to die ...", e); } try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/batman.json")) { final String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); } catch (final Exception e) { throw new RuntimeException("Test is going to die ...", e); } } @Test public void testListAllMovies() { final ResteasyClient client = (ResteasyClient)ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); final List<Movie> movies = proxy.listMovies(); System.out.println(movies); } @Test public void testMovieByImdbId() { final String transformerImdbId = "tt0418279"; final ResteasyClient client = (ResteasyClient) ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); final Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); final Movie movies = proxy.movieByImdbId(transformerImdbId); System.out.println(movies); } @Test public void testAddMovie() { final ResteasyClient client = (ResteasyClient) ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); moviesResponse = proxy.addMovie(transformerMovie); if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); System.out.println("Response Code: " + moviesResponse.getStatus()); } @Test public void testAddMovieMultiConnection() { final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); final ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine(httpClient); final ResteasyClient client = ((ResteasyClientBuilder) ClientBuilder.newBuilder()).httpEngine(engine).build(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); final Response batmanResponse = proxy.addMovie(batmanMovie); final Response transformerResponse = proxy.addMovie(transformerMovie); if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); } if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); } batmanResponse.close(); transformerResponse.close(); cm.close(); } @Test public void testDeleteMovie() { final ResteasyClient client = (ResteasyClient) ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); moviesResponse = proxy.deleteMovie(batmanMovie.getImdbId()); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println(moviesResponse.readEntity(String.class)); throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); System.out.println("Response Code: " + moviesResponse.getStatus()); } @Test public void testUpdateMovie() { final ResteasyClient client = (ResteasyClient) ClientBuilder.newClient(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); batmanMovie.setTitle("Batman Begins"); moviesResponse = proxy.updateMovie(batmanMovie); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); System.out.println("Response Code: " + moviesResponse.getStatus()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/resteasy/src/main/java/com/baeldung/filter/CORSFilter.java
web-modules/resteasy/src/main/java/com/baeldung/filter/CORSFilter.java
package com.baeldung.filter; import java.io.IOException; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerResponseContext; import jakarta.ws.rs.container.ContainerResponseFilter; public class CORSFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { responseContext.getHeaders().add("Access-Control-Allow-Origin", "*"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/resteasy/src/main/java/com/baeldung/model/Movie.java
web-modules/resteasy/src/main/java/com/baeldung/model/Movie.java
package com.baeldung.model; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "movie", propOrder = { "imdbId", "title" }) public class Movie { protected String imdbId; protected String title; public Movie(String imdbId, String title) { this.imdbId = imdbId; this.title = title; } public Movie() {} public String getImdbId() { return imdbId; } public void setImdbId(String imdbId) { this.imdbId = imdbId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Movie movie = (Movie) o; if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null) return false; return title != null ? title.equals(movie.title) : movie.title == null; } @Override public int hashCode() { int result = imdbId != null ? imdbId.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); return result; } @Override public String toString() { return "Movie{" + "imdbId='" + imdbId + '\'' + ", title='" + title + '\'' + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/resteasy/src/main/java/com/baeldung/server/RestEasyServices.java
web-modules/resteasy/src/main/java/com/baeldung/server/RestEasyServices.java
package com.baeldung.server; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.core.Application; import java.util.HashSet; import java.util.Map; import java.util.Set; @ApplicationPath("/rest") public class RestEasyServices extends Application { private Set<Object> singletons = new HashSet<Object>(); public RestEasyServices() { singletons.add(new MovieCrudService()); } @Override public Set<Object> getSingletons() { return singletons; } @Override public Set<Class<?>> getClasses() { return super.getClasses(); } @Override public Map<String, Object> getProperties() { return super.getProperties(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/resteasy/src/main/java/com/baeldung/server/MovieCrudService.java
web-modules/resteasy/src/main/java/com/baeldung/server/MovieCrudService.java
package com.baeldung.server; import com.baeldung.model.Movie; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Path("/movies") public class MovieCrudService { private Map<String, Movie> inventory = new HashMap<String, Movie>(); @GET @Path("/") @Produces({ MediaType.TEXT_PLAIN }) public Response index() { return Response.status(200).header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization") .header("Access-Control-Allow-Credentials", "true") .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD").entity("").build(); } @GET @Path("/getinfo") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling getinfo for a given ImdbID***"); if (inventory.containsKey(imdbId)) { return inventory.get(imdbId); } else return null; } @POST @Path("/addmovie") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response addMovie(Movie movie) { System.out.println("*** Calling addMovie ***"); if (null != inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build(); } inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.CREATED).build(); } @PUT @Path("/updatemovie") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response updateMovie(Movie movie) { System.out.println("*** Calling updateMovie ***"); if (null == inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build(); } @DELETE @Path("/deletemovie") public Response deleteMovie(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling deleteMovie ***"); if (null == inventory.get(imdbId)) { return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete") .build(); } inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } @GET @Path("/listmovies") @Produces({ "application/json" }) public List<Movie> listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/resteasy/src/main/java/com/baeldung/client/ServicesInterface.java
web-modules/resteasy/src/main/java/com/baeldung/client/ServicesInterface.java
package com.baeldung.client; import com.baeldung.model.Movie; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import java.util.List; @Path("/movies") public interface ServicesInterface { @GET @Path("/getinfo") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Movie movieByImdbId(@QueryParam("imdbId") String imdbId); @GET @Path("/listmovies") @Produces({ "application/json" }) List<Movie> listMovies(); @POST @Path("/addmovie") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Response addMovie(Movie movie); @PUT @Path("/updatemovie") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) Response updateMovie(Movie movie); @DELETE @Path("/deletemovie") Response deleteMovie(@QueryParam("imdbId") String imdbId); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-threads/src/test/java/com/baeldung/threading/ThreadPoolTaskExecutorUnitTest.java
spring-threads/src/test/java/com/baeldung/threading/ThreadPoolTaskExecutorUnitTest.java
package com.baeldung.threading; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import org.junit.Assert; import org.junit.Test; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; public class ThreadPoolTaskExecutorUnitTest { void startThreads(ThreadPoolTaskExecutor taskExecutor, CountDownLatch countDownLatch, int numThreads) { for (int i = 0; i < numThreads; i++) { taskExecutor.execute(() -> { try { Thread.sleep(100L * ThreadLocalRandom.current().nextLong(1, 10)); countDownLatch.countDown(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } } @Test public void whenUsingDefaults_thenSingleThread() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.afterPropertiesSet(); CountDownLatch countDownLatch = new CountDownLatch(10); this.startThreads(taskExecutor, countDownLatch, 10); while (countDownLatch.getCount() > 0) { Assert.assertEquals(1, taskExecutor.getPoolSize()); } } @Test public void whenCorePoolSizeFive_thenFiveThreads() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.afterPropertiesSet(); CountDownLatch countDownLatch = new CountDownLatch(10); this.startThreads(taskExecutor, countDownLatch, 10); while (countDownLatch.getCount() > 0) { Assert.assertEquals(5, taskExecutor.getPoolSize()); } } @Test public void whenCorePoolSizeFiveAndMaxPoolSizeTen_thenFiveThreads() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.afterPropertiesSet(); CountDownLatch countDownLatch = new CountDownLatch(10); this.startThreads(taskExecutor, countDownLatch, 10); while (countDownLatch.getCount() > 0) { Assert.assertEquals(5, taskExecutor.getPoolSize()); } } @Test public void whenCorePoolSizeFiveAndMaxPoolSizeTenAndQueueCapacityZero_thenTenThreads() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.setQueueCapacity(0); taskExecutor.afterPropertiesSet(); CountDownLatch countDownLatch = new CountDownLatch(10); this.startThreads(taskExecutor, countDownLatch, 10); while (countDownLatch.getCount() > 0) { Assert.assertEquals(10, taskExecutor.getPoolSize()); } } @Test public void whenCorePoolSizeFiveAndMaxPoolSizeTenAndQueueCapacityTen_thenTenThreads() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.setQueueCapacity(10); taskExecutor.afterPropertiesSet(); CountDownLatch countDownLatch = new CountDownLatch(20); this.startThreads(taskExecutor, countDownLatch, 20); while (countDownLatch.getCount() > 0) { Assert.assertEquals(10, taskExecutor.getPoolSize()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-credhub/src/test/java/com/baeldung/controller/CredentialServiceUnitTest.java
spring-credhub/src/test/java/com/baeldung/controller/CredentialServiceUnitTest.java
package com.baeldung.controller; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import java.util.HashMap; import java.util.List; import java.util.Map; import org.assertj.core.util.DateUtil; import org.junit.Ignore; import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.credhub.support.CredentialPermission; import org.springframework.credhub.support.permissions.Operation; import com.baeldung.model.Credential; import com.baeldung.service.CredentialService; @Ignore @ExtendWith(MockitoExtension.class) public class CredentialServiceUnitTest { @InjectMocks private CredentialService credentialService; @Test public void whenGeneratePassword_thenReturnNewPassword() { String orderApiKey = credentialService.generatePassword("order_api_key"); assertFalse(orderApiKey.isEmpty()); } @Test public void whenWriteCredential_thenReturnSuccess() { Map<String, Object> value = new HashMap<>(); value.put("end_date", DateUtil.now()); value.put("start_date", DateUtil.yesterday()); Credential credential = new Credential(); credential.setName("order_config_json"); credential.setType("json"); credential.setValue(value); String result = credentialService.writeCredential(credential); assertThat(result).isEqualTo("Credential:order_config_json written successfully!"); } @Test public void whenRotatePassword_thenRegenerateNewPassword() { String orderApiKey = credentialService.rotatePassword("order_api_key"); assertThat(orderApiKey).isEqualTo("Credential:order_api_key re-generated successfully!"); } @Test public void whenRevokePassword_thenDeletePassword() { String orderApiKey = credentialService.deletePassword("order_api_key"); assertThat(orderApiKey).isEqualTo("Credential:order_api_key deleted successfully!"); } @Test public void whenRetrieveExistingCredential_thenReturnCredentialValue() { String orderConfigJson = credentialService.getPassword("order_config_json"); assertFalse(orderConfigJson.isEmpty()); } @Test public void whenCredentialPermissionCreated_thenAddToCredential() { CredentialPermission orderConfig = credentialService.addCredentialPermission("order_config_json"); List<Operation> operations = orderConfig.getPermission() .getOperations(); String identity = orderConfig.getPermission() .getActor() .getIdentity(); CredentialPermission newOrderConfig = credentialService.getCredentialPermission("order_config_json"); List<Operation> newOperations = newOrderConfig.getPermission() .getOperations(); String newIdentity = newOrderConfig.getPermission() .getActor() .getIdentity(); assertThat(operations.size() == newOperations.size() && operations.containsAll(newOperations) && newOperations.containsAll(operations)); assertThat(identity).isEqualTo(newIdentity); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-credhub/src/main/java/com/baeldung/OrderApplication.java
spring-credhub/src/main/java/com/baeldung/OrderApplication.java
package com.baeldung; public class OrderApplication { public static void main(String[] args) { System.out.println("Hello world!"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-credhub/src/main/java/com/baeldung/controller/CredentialController.java
spring-credhub/src/main/java/com/baeldung/controller/CredentialController.java
package com.baeldung.controller; import com.baeldung.model.Credential; import com.baeldung.service.CredentialService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.credhub.support.CredentialPermission; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class CredentialController { @Autowired CredentialService credentialService; @PostMapping("/credentials") public ResponseEntity<String> generatePassword(@RequestBody String credentialName) { return new ResponseEntity<>(credentialService.generatePassword(credentialName), HttpStatus.OK); } @PutMapping("/credentials") public ResponseEntity<String> writeJSONCredential(@RequestBody Credential secret) { return new ResponseEntity<>(credentialService.writeCredential(secret), HttpStatus.OK); } @PostMapping("/credentials/rotate") public ResponseEntity<String> rotatePassword(@RequestBody String credentialName) { return new ResponseEntity<>(credentialService.rotatePassword(credentialName), HttpStatus.OK); } @DeleteMapping("/credentials") public ResponseEntity<String> deletePassword(@RequestBody String credentialName) { return new ResponseEntity<>(credentialService.deletePassword(credentialName), HttpStatus.OK); } @GetMapping("/credentials") public ResponseEntity<String> getPassword(@RequestBody String credentialName) { return new ResponseEntity<>(credentialService.getPassword(credentialName), HttpStatus.OK); } @PostMapping("/permissions") public ResponseEntity<CredentialPermission> addPermission(@RequestBody String credentialName) { return new ResponseEntity<>(credentialService.addCredentialPermission(credentialName), HttpStatus.OK); } @GetMapping("/permissions") public ResponseEntity<CredentialPermission> getPermission(@RequestBody String credentialName) { return new ResponseEntity<>(credentialService.getCredentialPermission(credentialName), HttpStatus.OK); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-credhub/src/main/java/com/baeldung/controller/OrderController.java
spring-credhub/src/main/java/com/baeldung/controller/OrderController.java
package com.baeldung.controller; import static java.time.LocalDate.now; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.baeldung.model.Order; import com.baeldung.service.CredentialService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/orders") public class OrderController { @Autowired CredentialService credentialService; public OrderController(CredentialService credentialService) { this.credentialService = credentialService; } @GetMapping public ResponseEntity<Collection<Order>> getAllOrders() { try { String apiKey = credentialService.getPassword("api_key"); return new ResponseEntity<>(getOrderList(apiKey), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } } private List<Order> getOrderList(String apiKey) throws Exception { if (!credentialMatch(apiKey)) throw new Exception(); Order order = new Order(); order.setId(123L); order.setCustomerName("Craig"); order.setOrderDate(now()); List<Order> orderList = new ArrayList<>(); orderList.add(order); return orderList; } private boolean credentialMatch(String credValue) { //logic to check credValue return true; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-credhub/src/main/java/com/baeldung/service/CredentialService.java
spring-credhub/src/main/java/com/baeldung/service/CredentialService.java
package com.baeldung.service; import java.util.Map; import java.util.UUID; import org.springframework.credhub.core.CredHubOperations; import org.springframework.credhub.core.credential.CredHubCredentialOperations; import org.springframework.credhub.core.permissionV2.CredHubPermissionV2Operations; import org.springframework.credhub.support.CredentialDetails; import org.springframework.credhub.support.CredentialPermission; import org.springframework.credhub.support.CredentialRequest; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.certificate.CertificateCredential; import org.springframework.credhub.support.certificate.CertificateCredentialRequest; import org.springframework.credhub.support.json.JsonCredentialRequest; import org.springframework.credhub.support.password.PasswordCredential; import org.springframework.credhub.support.password.PasswordCredentialRequest; import org.springframework.credhub.support.password.PasswordParameters; import org.springframework.credhub.support.password.PasswordParametersRequest; import org.springframework.credhub.support.permissions.Operation; import org.springframework.credhub.support.permissions.Permission; import org.springframework.credhub.support.rsa.RsaCredential; import org.springframework.credhub.support.rsa.RsaCredentialRequest; import org.springframework.credhub.support.ssh.SshCredential; import org.springframework.credhub.support.ssh.SshCredentialRequest; import org.springframework.credhub.support.user.UserCredential; import org.springframework.credhub.support.user.UserCredentialRequest; import org.springframework.credhub.support.value.ValueCredential; import org.springframework.credhub.support.value.ValueCredentialRequest; import com.baeldung.model.Credential; public class CredentialService { private final CredHubCredentialOperations credentialOperations; private final CredHubPermissionV2Operations permissionOperations; public CredentialService(CredHubOperations credHubOperations) { this.credentialOperations = credHubOperations.credentials(); this.permissionOperations = credHubOperations.permissionsV2(); } public String generatePassword(String name) { try { SimpleCredentialName credentialName = new SimpleCredentialName(name); PasswordParameters parameters = PasswordParameters.builder() .length(24) .excludeUpper(false) .excludeLower(false) .includeSpecial(true) .excludeNumber(false) .build(); CredentialDetails<PasswordCredential> generatedCred = credentialOperations.generate(PasswordParametersRequest.builder() .name(credentialName) .parameters(parameters) .build()); return generatedCred.getValue() .getPassword(); } catch (Exception e) { return null; } } public String writeCredential(Credential credential) { try { SimpleCredentialName credentialName = new SimpleCredentialName(credential.getName()); CredentialRequest request = null; Map<String, Object> value = credential.getValue(); switch (credential.getType()) { case "value": ValueCredential valueCredential = new ValueCredential((String) value.get("value")); request = ValueCredentialRequest.builder() .name(credentialName) .value(valueCredential) .build(); break; case "json": request = JsonCredentialRequest.builder() .name(credentialName) .value(value) .build(); break; case "user": UserCredential userCredential = new UserCredential((String) value.get("username"), (String) value.get("password")); request = UserCredentialRequest.builder() .name(credentialName) .value(userCredential) .build(); break; case "password": PasswordCredential passwordCredential = new PasswordCredential((String) value.get("password")); request = PasswordCredentialRequest.builder() .name(credentialName) .value(passwordCredential) .build(); break; case "certificate": CertificateCredential certificateCredential = new CertificateCredential((String) value.get("certificate"), (String) value.get("certificate_authority"), (String) value.get("private_key")); request = CertificateCredentialRequest.builder() .name(credentialName) .value(certificateCredential) .build(); break; case "rsa": RsaCredential rsaCredential = new RsaCredential((String) value.get("public_key"), (String) value.get("private_key")); request = RsaCredentialRequest.builder() .name(credentialName) .value(rsaCredential) .build(); break; case "ssh": SshCredential sshCredential = new SshCredential((String) value.get("public_key"), (String) value.get("private_key")); request = SshCredentialRequest.builder() .name(credentialName) .value(sshCredential) .build(); break; default: } if (request != null) { credentialOperations.write(request); } return "Credential:" + credentialName + " written successfully!"; } catch (Exception e) { return "Error! Unable to write credential"; } } public String rotatePassword(String name) { try { SimpleCredentialName credentialName = new SimpleCredentialName(name); CredentialDetails<PasswordCredential> oldPassword = credentialOperations.getByName(credentialName, PasswordCredential.class); CredentialDetails<PasswordCredential> newPassword = credentialOperations.regenerate(credentialName, PasswordCredential.class); return "Credential:" + credentialName + " re-generated successfully!"; } catch (Exception e) { return "Error! Unable to re-generate credential"; } } public String deletePassword(String name) { try { SimpleCredentialName credentialName = new SimpleCredentialName(name); credentialOperations.deleteByName(credentialName); return "Credential:" + credentialName + " deleted successfully!"; } catch (Exception e) { return "Error! Unable to delete credential"; } } public String getPassword(String name) { try { SimpleCredentialName credentialName = new SimpleCredentialName(name); return credentialOperations.getByName(credentialName, PasswordCredential.class) .getValue() .getPassword(); } catch (Exception e) { return null; } } public CredentialPermission addCredentialPermission(String name) { SimpleCredentialName credentialName = new SimpleCredentialName(name); try { Permission permission = Permission.builder() .app(UUID.randomUUID() .toString()) .operations(Operation.READ, Operation.WRITE) .user("u101") .build(); CredentialPermission credentialPermission = permissionOperations.addPermissions(credentialName, permission); return credentialPermission; } catch (Exception e) { return null; } } public CredentialPermission getCredentialPermission(String name) { try { return permissionOperations.getPermissions(name); } catch (Exception e) { return null; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-credhub/src/main/java/com/baeldung/model/Order.java
spring-credhub/src/main/java/com/baeldung/model/Order.java
package com.baeldung.model; import java.time.LocalDate; import lombok.Getter; import lombok.Setter; @Getter @Setter public class Order { private Long id; private String customerName; private LocalDate orderDate; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-credhub/src/main/java/com/baeldung/model/Credential.java
spring-credhub/src/main/java/com/baeldung/model/Credential.java
package com.baeldung.model; import java.util.Map; import lombok.Getter; import lombok.Setter; @Getter @Setter public class Credential { Map<String, Object> value; String type; String name; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/test/java/com/baeldung/gcp/firebase/auth/UserControllerLiveTest.java
gcp-firebase/src/test/java/com/baeldung/gcp/firebase/auth/UserControllerLiveTest.java
package com.baeldung.gcp.firebase.auth; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; 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.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import com.jayway.jsonpath.JsonPath; import net.bytebuddy.utility.RandomString; @SpringBootTest @AutoConfigureMockMvc class UserControllerLiveTest { private static final String GET_USER_API_PATH = "/user"; private static final String CREATE_USER_API_PATH = "/user"; private static final String LOGIN_USER_API_PATH = "/user/login"; private static final String REFRESH_TOKEN_API_PATH = "/user/refresh-token"; @Autowired private MockMvc mockMvc; @Test void whenCreatingUserWithValidDetails_thenUserCreationSucceeds() throws Exception { // Set up test data String emailId = RandomString.make() + "@baeldung.it"; String password = RandomString.make(); String requestBody = String.format(""" { "emailId" : "%s", "password" : "%s" } """, emailId, password); // Invoke API under test mockMvc.perform(post(CREATE_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()); } @Test void whenCreatingUserWithExistingEmail_thenUserCreationFails() throws Exception { // Set up test data String emailId = RandomString.make() + "@baeldung.it"; String password = RandomString.make(); String requestBody = String.format(""" { "emailId" : "%s", "password" : "%s" } """, emailId, password); // Invoke create user API mockMvc.perform(post(CREATE_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()); // Invoke create user API with same emailId mockMvc.perform(post(CREATE_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isConflict()) .andExpect(jsonPath("$.status").value(HttpStatus.CONFLICT.value())) .andExpect(jsonPath("$.detail").value("Account with given email-id already exists")); } @Test void whenLoginWithValidCredentials_thenTokenReturned() throws Exception { // Set up test data String emailId = RandomString.make() + "@baeldung.it"; String password = RandomString.make(); String requestBody = String.format(""" { "emailId" : "%s", "password" : "%s" } """, emailId, password); // Invoke create user API mockMvc.perform(post(CREATE_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()); // Invoke API under test mockMvc.perform(post(LOGIN_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()) .andExpect(jsonPath("$.idToken").exists()); } @Test void whenLoginWithInvalidCredentials_thenTokenNotReturned() throws Exception { // Set up test data String emailId = RandomString.make() + "@baeldung.it"; String password = RandomString.make(); String requestBody = String.format(""" { "emailId" : "%s", "password" : "%s" } """, emailId, password); // Invoke API under test mockMvc.perform(post(LOGIN_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.status").value(HttpStatus.UNAUTHORIZED.value())) .andExpect(jsonPath("$.detail").value("Invalid login credentials provided")); } @Test void whenRetrievingUserWithValidToken_thenDetailsAreReturned() throws Exception { // Set up test data String emailId = RandomString.make().toLowerCase() + "@baeldung.it"; String password = RandomString.make(); String requestBody = String.format(""" { "emailId" : "%s", "password" : "%s" } """, emailId, password); // Invoke create user API mockMvc.perform(post(CREATE_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()); // Invoke user login API and extract token MvcResult loginResult = mockMvc.perform(post(LOGIN_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()) .andReturn(); String token = JsonPath.read(loginResult.getResponse().getContentAsString(), "$.idToken"); // Invoke API under test mockMvc.perform(get(GET_USER_API_PATH) .with(csrf()) .header("Authorization", "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.email").value(emailId)) .andExpect(jsonPath("$.emailVerified").value(true)); } @Test void whenExchangingValidRefreshToken_thenNewIdTokenReturned() throws Exception { // Set up test data String emailId = RandomString.make().toLowerCase() + "@baeldung.it"; String password = RandomString.make(); String requestBody = String.format(""" { "emailId" : "%s", "password" : "%s" } """, emailId, password); // Invoke create user API mockMvc.perform(post(CREATE_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()); // Invoke user login API and extract refresh token MvcResult loginResult = mockMvc.perform(post(LOGIN_USER_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()) .andReturn(); String refreshToken = JsonPath.read(loginResult.getResponse().getContentAsString(), "$.refreshToken"); // Invoke API under test and extract ID token requestBody = String.format(""" { "refreshToken" : "%s" } """, refreshToken); MvcResult refreshTokenResult = mockMvc.perform(post(REFRESH_TOKEN_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isOk()) .andExpect(jsonPath("$.id_token").exists()) .andReturn(); String idToken = JsonPath.read(refreshTokenResult.getResponse().getContentAsString(), "$.id_token"); // Verify ID token invokes private API mockMvc.perform(get(GET_USER_API_PATH) .with(csrf()) .header("Authorization", "Bearer " + idToken)) .andExpect(status().isOk()) .andExpect(jsonPath("$.email").value(emailId)) .andExpect(jsonPath("$.emailVerified").value(true)); } @Test void whenExchangingInvalidRefreshToken_thenNewIdTokenNotReturned() throws Exception { // Set up test data String invalidRefreshToken = RandomString.make(); String requestBody = String.format(""" { "refreshToken" : "%s" } """, invalidRefreshToken); // Invoke API under test mockMvc.perform(post(REFRESH_TOKEN_API_PATH) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(requestBody)) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.status").value(HttpStatus.FORBIDDEN.value())) .andExpect(jsonPath("$.detail").value("Invalid refresh token provided")); } @Test void whenInvalidToken_thenApiAccessDenied() throws Exception { // Set up test data String invalidToken = RandomString.make(); // Invoke API under test mockMvc.perform(get(GET_USER_API_PATH) .with(csrf()) .header("Authorization", "Bearer " + invalidToken)) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.status").value(HttpStatus.UNAUTHORIZED.value())) .andExpect(jsonPath("$.detail").value("Authentication failure: Token missing, invalid or expired"));; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/test/java/com/baeldung/gcp/firebase/publisher/controller/FirebasePublisherControllerLiveTest.java
gcp-firebase/src/test/java/com/baeldung/gcp/firebase/publisher/controller/FirebasePublisherControllerLiveTest.java
package com.baeldung.gcp.firebase.publisher.controller; import static org.junit.jupiter.api.Assertions.*; import java.net.URI; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class FirebasePublisherControllerLiveTest { @LocalServerPort int serverPort; @Autowired TestRestTemplate restTemplate; @Test void testWhenPostTopicMessage_thenSucess() throws Exception{ URI uri = new URI("http://localhost:" + serverPort + "/topics/my-topic"); ResponseEntity<String> response = restTemplate.postForEntity(uri, "Hello, world", String.class); assertNotNull(response); assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); assertNotNull(response.getBody()); } @Test void testWhenPostClientMessage_thenSucess() throws Exception{ URI uri = new URI("http://localhost:" + serverPort + "/clients/fake-registration1"); ResponseEntity<String> response = restTemplate.postForEntity(uri, "Hello, world", String.class); assertNotNull(response); assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); assertNotNull(response.getBody()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/test/java/com/baeldung/gcp/firebase/firestore/TaskCrudLiveTest.java
gcp-firebase/src/test/java/com/baeldung/gcp/firebase/firestore/TaskCrudLiveTest.java
package com.baeldung.gcp.firebase.firestore; import static org.assertj.core.api.Assertions.assertThat; import static org.instancio.Select.field; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import org.instancio.Instancio; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.testcontainers.containers.FirestoreEmulatorContainer; import org.testcontainers.shaded.org.awaitility.Awaitility; import org.testcontainers.utility.DockerImageName; import com.google.cloud.NoCredentials; import com.google.cloud.firestore.DocumentReference; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.FirestoreOptions; import com.google.cloud.firestore.QueryDocumentSnapshot; import net.bytebuddy.utility.RandomString; @SpringBootTest @ActiveProfiles("live-test") class TaskCrudLiveTest { @Autowired private Firestore firestore; private static FirestoreEmulatorContainer firestoreEmulatorContainer = new FirestoreEmulatorContainer( DockerImageName.parse("gcr.io/google.com/cloudsdktool/google-cloud-cli:488.0.0-emulators") ); @TestConfiguration static class FirestoreTestConfiguration { @Bean public Firestore firestore() { firestoreEmulatorContainer.start(); FirestoreOptions options = FirestoreOptions .getDefaultInstance() .toBuilder() .setProjectId(RandomString.make().toLowerCase()) .setCredentials(NoCredentials.getInstance()) .setHost(firestoreEmulatorContainer.getEmulatorEndpoint()) .build(); return options.getService(); } } @Test void whenCreatingTask_thenTaskIsSavedInFirestoreWithAutoGeneratedId() throws Exception { // Set up test data Task task = Instancio.create(Task.class); // Save task in Firestore DocumentReference taskReference = firestore .collection(Task.PATH) .document(); taskReference.set(task); // Verify task is saved with auto-generated ID String taskId = taskReference.getId(); assertThat(taskId).isNotBlank(); Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> { DocumentSnapshot taskSnapshot = firestore .collection(Task.PATH) .document(taskId) .get().get(); assertThat(taskSnapshot.exists()) .isTrue(); }); } @Test void whenCreatingTaskWithCustomTaskId_thenTaskIsSavedInFirestore() throws Exception { // Set up test data Task task = Instancio.create(Task.class); String taskId = Instancio.create(String.class); // Save task in Firestore with custom ID firestore .collection(Task.PATH) .document(taskId) .set(task); // Verify task is saved Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> { DocumentSnapshot taskSnapshot = firestore .collection(Task.PATH) .document(taskId) .get().get(); assertThat(taskSnapshot.exists()) .isTrue(); }); } @Test void whenRetrievingExistingTask_thenCorrectTaskIsReturned() throws Exception { // Set up test data Task task = Instancio.create(Task.class); String taskId = Instancio.create(String.class); // Save task in Firestore firestore .collection(Task.PATH) .document(taskId) .set(task) .get(); // Retrieve the task DocumentSnapshot taskSnapshot = firestore .collection(Task.PATH) .document(taskId) .get().get(); // Verify correct task is retrieved Task retrievedTask = taskSnapshot.toObject(Task.class); assertThat(retrievedTask) .usingRecursiveComparison() .isEqualTo(task); } @Test void whenRetrievingTasksWithStatusQuery_thenMatchingTasksAreReturned() throws Exception { // Set up test data Task completedTask = Instancio.of(Task.class) .set(field(Task::getStatus), "COMPLETED") .create(); Task inProgressTask = Instancio.of(Task.class) .set(field(Task::getStatus), "IN_PROGRESS") .create(); Task anotherCompletedTask = Instancio.of(Task.class) .set(field(Task::getStatus), "COMPLETED") .create(); List<Task> tasks = List.of(completedTask, inProgressTask, anotherCompletedTask); // Save tasks in Firestore for (Task task: tasks) { firestore .collection(Task.PATH) .add(task) .get(); } // Retrieve completed tasks List<QueryDocumentSnapshot> retrievedTaskSnapshots = firestore .collection(Task.PATH) .whereEqualTo("status", "COMPLETED") .get().get().getDocuments(); // Verify only matching tasks are retrieved List<Task> retrievedTasks = retrievedTaskSnapshots .stream() .map(snapshot -> snapshot.toObject(Task.class)) .toList(); assertThat(retrievedTasks) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder(completedTask, anotherCompletedTask); } @Test @DirtiesContext void whenRetrievingTaskDueWithinNextWeek_thenCorrectTaskIsReturned() throws Exception { // Create task with due date within a week Date dueDate = Date.from(Instant.now().plus(5, ChronoUnit.DAYS)); Task task = Instancio.of(Task.class) .set(field(Task::getDueDate), dueDate) .create(); firestore .collection(Task.PATH) .add(task) .get(); // Retrieve tasks due within the next week List<QueryDocumentSnapshot> retrievedTaskSnapshots = firestore .collection(Task.PATH) .whereGreaterThanOrEqualTo("dueDate", Date.from(Instant.now())) .whereLessThanOrEqualTo("dueDate", Date.from(Instant.now().plus(7, ChronoUnit.DAYS))) .get().get().getDocuments(); // Verify the correct task is retrieved assertThat(retrievedTaskSnapshots) .hasSize(1) .map(snapshot -> snapshot.toObject(Task.class)) .first() .satisfies(retrievedTask -> { assertThat(retrievedTask) .usingRecursiveComparison() .isEqualTo(task); }); } @Test void whenUpdatingTask_thenTaskIsUpdatedInFirestore() throws Exception { // Save initial task in Firestore String taskId = Instancio.create(String.class); Task initialTask = Instancio.of(Task.class) .set(field(Task::getStatus), "IN_PROGRESS") .create(); firestore .collection(Task.PATH) .document(taskId) .set(initialTask); // Ensure the task is created Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> { DocumentSnapshot taskSnapshot = firestore .collection(Task.PATH) .document(taskId) .get().get(); assertThat(taskSnapshot.exists()) .isTrue(); }); // Update the task Task updatedTask = initialTask; updatedTask.setStatus("COMPLETED"); firestore .collection(Task.PATH) .document(taskId) .set(initialTask); // Verify the task was updated correctly Task retrievedTask = firestore .collection(Task.PATH) .document(taskId) .get().get() .toObject(Task.class); assertThat(retrievedTask) .usingRecursiveComparison() .isNotEqualTo(initialTask) .ignoringFields("status") .isEqualTo(initialTask); } @Test void whenDeletingTask_thenTaskIsRemovedFromFirestore() throws Exception { // Save task in Firestore Task task = Instancio.create(Task.class); String taskId = Instancio.create(String.class); firestore .collection(Task.PATH) .document(taskId) .set(task); // Ensure the task is created Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> { DocumentSnapshot taskSnapshot = firestore .collection(Task.PATH) .document(taskId) .get().get(); assertThat(taskSnapshot.exists()) .isTrue(); }); // Delete the task firestore .collection(Task.PATH) .document(taskId) .delete(); // Assert that the task is deleted Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> { DocumentSnapshot taskSnapshot = firestore .collection(Task.PATH) .document(taskId) .get().get(); assertThat(taskSnapshot.exists()) .isFalse(); }); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/UserService.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/UserService.java
package com.baeldung.gcp.firebase.auth; import org.springframework.stereotype.Service; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.UserRecord; import com.google.firebase.auth.UserRecord.CreateRequest; @Service public class UserService { private static final String DUPLICATE_ACCOUNT_ERROR = "EMAIL_EXISTS"; private final FirebaseAuth firebaseAuth; private final AuthenticatedUserIdProvider authenticatedUserIdProvider; public UserService(FirebaseAuth firebaseAuth, AuthenticatedUserIdProvider authenticatedUserIdProvider) { this.firebaseAuth = firebaseAuth; this.authenticatedUserIdProvider = authenticatedUserIdProvider; } public void create(String emailId, String password) throws FirebaseAuthException { CreateRequest request = new CreateRequest(); request.setEmail(emailId); request.setPassword(password); request.setEmailVerified(Boolean.TRUE); try { firebaseAuth.createUser(request); } catch (FirebaseAuthException exception) { if (exception.getMessage().contains(DUPLICATE_ACCOUNT_ERROR)) { throw new AccountAlreadyExistsException("Account with given email-id already exists"); } throw exception; } } public void logout() throws FirebaseAuthException { String userId = authenticatedUserIdProvider.getUserId(); firebaseAuth.revokeRefreshTokens(userId); } public UserRecord retrieve() throws FirebaseAuthException { String userId = authenticatedUserIdProvider.getUserId(); return firebaseAuth.getUser(userId); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/SecurityConfiguration.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/SecurityConfiguration.java
package com.baeldung.gcp.firebase.auth; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration public class SecurityConfiguration { private static final String[] WHITELISTED_API_ENDPOINTS = { "/user", "/user/login", "/user/refresh-token" }; private final TokenAuthenticationFilter tokenAuthenticationFilter; public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) { this.tokenAuthenticationFilter = tokenAuthenticationFilter; } @Bean public SecurityFilterChain configure(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authManager -> { authManager.requestMatchers(HttpMethod.POST, WHITELISTED_API_ENDPOINTS) .permitAll() .anyRequest() .authenticated(); }) .addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/AccountAlreadyExistsException.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/AccountAlreadyExistsException.java
package com.baeldung.gcp.firebase.auth; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; public class AccountAlreadyExistsException extends ResponseStatusException { public AccountAlreadyExistsException(String reason) { super(HttpStatus.CONFLICT, reason); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/InvalidLoginCredentialsException.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/InvalidLoginCredentialsException.java
package com.baeldung.gcp.firebase.auth; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; public class InvalidLoginCredentialsException extends ResponseStatusException { public InvalidLoginCredentialsException(String reason) { super(HttpStatus.UNAUTHORIZED, reason); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/AuthenticatedUserIdProvider.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/AuthenticatedUserIdProvider.java
package com.baeldung.gcp.firebase.auth; import java.util.Optional; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @Component public class AuthenticatedUserIdProvider { public String getUserId() { return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()) .map(Authentication::getPrincipal) .filter(String.class::isInstance) .map(String.class::cast) .orElseThrow(IllegalStateException::new); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/ApiExceptionHandler.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/ApiExceptionHandler.java
package com.baeldung.gcp.firebase.auth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ProblemDetail; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @RestControllerAdvice public class ApiExceptionHandler extends ResponseEntityExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class); @ExceptionHandler(ResponseStatusException.class) public ProblemDetail handle(ResponseStatusException exception) { log(exception); return ProblemDetail.forStatusAndDetail(exception.getStatusCode(), exception.getReason()); } @ExceptionHandler(Exception.class) public ProblemDetail handle(Exception exception) { log(exception); return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_IMPLEMENTED, "Something went wrong."); } private void log(Exception exception) { LOGGER.error("Exception encountered: {}", exception.getMessage(), exception); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/FirebaseAuthClient.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/FirebaseAuthClient.java
package com.baeldung.gcp.firebase.auth; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClient; @Component public class FirebaseAuthClient { private static final String API_KEY_PARAM = "key"; private static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; private static final String INVALID_CREDENTIALS_ERROR = "INVALID_LOGIN_CREDENTIALS"; private static final String INVALID_REFRESH_TOKEN_ERROR = "INVALID_REFRESH_TOKEN"; private static final String SIGN_IN_BASE_URL = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword"; private static final String REFRESH_TOKEN_BASE_URL = "https://securetoken.googleapis.com/v1/token"; private final String webApiKey; public FirebaseAuthClient(@Value("${com.baeldung.firebase.web-api-key}") String webApiKey) { this.webApiKey = webApiKey; } public FirebaseSignInResponse login(String emailId, String password) { FirebaseSignInRequest requestBody = new FirebaseSignInRequest(emailId, password, true); return sendSignInRequest(requestBody); } public RefreshTokenResponse exchangeRefreshToken(String refreshToken) { RefreshTokenRequest requestBody = new RefreshTokenRequest(REFRESH_TOKEN_GRANT_TYPE, refreshToken); return sendRefreshTokenRequest(requestBody); } private FirebaseSignInResponse sendSignInRequest(FirebaseSignInRequest firebaseSignInRequest) { try { return RestClient.create(SIGN_IN_BASE_URL) .post() .uri(uriBuilder -> uriBuilder .queryParam(API_KEY_PARAM, webApiKey) .build()) .body(firebaseSignInRequest) .contentType(MediaType.APPLICATION_JSON) .retrieve() .body(FirebaseSignInResponse.class); } catch (HttpClientErrorException exception) { if (exception.getResponseBodyAsString().contains(INVALID_CREDENTIALS_ERROR)) { throw new InvalidLoginCredentialsException("Invalid login credentials provided"); } throw exception; } } private RefreshTokenResponse sendRefreshTokenRequest(RefreshTokenRequest refreshTokenRequest) { try { return RestClient.create(REFRESH_TOKEN_BASE_URL) .post() .uri(uriBuilder -> uriBuilder .queryParam(API_KEY_PARAM, webApiKey) .build()) .body(refreshTokenRequest) .contentType(MediaType.APPLICATION_JSON) .retrieve() .body(RefreshTokenResponse.class); } catch (HttpClientErrorException exception) { if (exception.getResponseBodyAsString().contains(INVALID_REFRESH_TOKEN_ERROR)) { throw new InvalidRefreshTokenException("Invalid refresh token provided"); } throw exception; } } record FirebaseSignInRequest(String email, String password, boolean returnSecureToken) { } record FirebaseSignInResponse(String idToken, String refreshToken) { } record RefreshTokenRequest(String grant_type, String refresh_token) { } record RefreshTokenResponse(String id_token) { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/FirebaseAuthConfiguration.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/FirebaseAuthConfiguration.java
package com.baeldung.gcp.firebase.auth; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import com.google.auth.oauth2.GoogleCredentials; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.auth.FirebaseAuth; @Configuration public class FirebaseAuthConfiguration { @Value("classpath:/private-key.json") private Resource privateKey; @Bean public FirebaseApp firebaseApp() throws IOException { InputStream credentials = new ByteArrayInputStream(privateKey.getContentAsByteArray()); FirebaseOptions firebaseOptions = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(credentials)) .build(); return FirebaseApp.initializeApp(firebaseOptions); } @Bean public FirebaseAuth firebaseAuth(FirebaseApp firebaseApp) { return FirebaseAuth.getInstance(firebaseApp); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/TokenAuthenticationFilter.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/TokenAuthenticationFilter.java
package com.baeldung.gcp.firebase.auth; import java.io.IOException; import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ProblemDetail; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.FirebaseToken; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @Component public class TokenAuthenticationFilter extends OncePerRequestFilter { private static final String BEARER_PREFIX = "Bearer "; private static final String USER_ID_CLAIM = "user_id"; private static final String AUTHORIZATION_HEADER = "Authorization"; private final FirebaseAuth firebaseAuth; private final ObjectMapper objectMapper; public TokenAuthenticationFilter(FirebaseAuth firebaseAuth, ObjectMapper objectMapper) { this.firebaseAuth = firebaseAuth; this.objectMapper = objectMapper; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER); if (authorizationHeader != null && authorizationHeader.startsWith(BEARER_PREFIX)) { String token = authorizationHeader.replace(BEARER_PREFIX, ""); Optional<String> userId = extractUserIdFromToken(token); if (userId.isPresent()) { var authentication = new UsernamePasswordAuthenticationToken(userId.get(), null, null); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } else { setAuthErrorDetails(response); return; } } filterChain.doFilter(request, response); } private Optional<String> extractUserIdFromToken(String token) { try { FirebaseToken firebaseToken = firebaseAuth.verifyIdToken(token, true); String userId = String.valueOf(firebaseToken.getClaims().get(USER_ID_CLAIM)); return Optional.of(userId); } catch (FirebaseAuthException exception) { return Optional.empty(); } } private void setAuthErrorDetails(HttpServletResponse response) throws JsonProcessingException, IOException { HttpStatus unauthorized = HttpStatus.UNAUTHORIZED; response.setStatus(unauthorized.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(unauthorized, "Authentication failure: Token missing, invalid or expired"); response.getWriter().write(objectMapper.writeValueAsString(problemDetail)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/InvalidRefreshTokenException.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/InvalidRefreshTokenException.java
package com.baeldung.gcp.firebase.auth; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; public class InvalidRefreshTokenException extends ResponseStatusException { public InvalidRefreshTokenException(String reason) { super(HttpStatus.FORBIDDEN, reason); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/UserController.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/UserController.java
package com.baeldung.gcp.firebase.auth; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import com.baeldung.gcp.firebase.auth.FirebaseAuthClient.FirebaseSignInResponse; import com.baeldung.gcp.firebase.auth.FirebaseAuthClient.RefreshTokenResponse; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.UserRecord; @RestController @RequestMapping("/user") public class UserController { private final UserService userService; private final FirebaseAuthClient firebaseAuthClient; public UserController(UserService userService, FirebaseAuthClient firebaseAuthClient) { this.userService = userService; this.firebaseAuthClient = firebaseAuthClient; } @GetMapping public ResponseEntity<UserRecord> getUser() throws FirebaseAuthException { UserRecord userRecord = userService.retrieve(); return ResponseEntity.ok(userRecord); } @PostMapping public ResponseEntity<Void> createUser(@RequestBody CreateUserRequest request) throws FirebaseAuthException { userService.create(request.emailId(), request.password()); return ResponseEntity.ok().build(); } @PostMapping("/login") public ResponseEntity<FirebaseSignInResponse> loginUser(@RequestBody LoginUserRequest request) { FirebaseSignInResponse response = firebaseAuthClient.login(request.emailId(), request.password()); return ResponseEntity.ok(response); } @PostMapping("/refresh-token") public ResponseEntity<RefreshTokenResponse> refreshToken(@RequestBody RefreshTokenRequest request) { RefreshTokenResponse response = firebaseAuthClient.exchangeRefreshToken(request.refreshToken()); return ResponseEntity.ok(response); } @PostMapping("/logout") public ResponseEntity<Void> logoutUser() throws FirebaseAuthException { userService.logout(); return ResponseEntity.ok().build(); } record CreateUserRequest(String emailId, String password) {} record LoginUserRequest(String emailId, String password) {} record RefreshTokenRequest(String refreshToken) {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/Application.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/auth/Application.java
package com.baeldung.gcp.firebase.auth; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/FirebasePublisherApplication.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/FirebasePublisherApplication.java
package com.baeldung.gcp.firebase.publisher; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FirebasePublisherApplication { public static void main(String[] args ) { SpringApplication.run(FirebasePublisherApplication.class,args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/controller/FirebasePublisherController.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/controller/FirebasePublisherController.java
package com.baeldung.gcp.firebase.publisher.controller; import java.util.List; import java.util.Arrays; import java.util.stream.Collectors; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.google.firebase.messaging.AndroidConfig; import com.google.firebase.messaging.AndroidFcmOptions; import com.google.firebase.messaging.ApnsConfig; import com.google.firebase.messaging.BatchResponse; import com.google.firebase.messaging.FcmOptions; import com.google.firebase.messaging.FirebaseMessaging; import com.google.firebase.messaging.FirebaseMessagingException; import com.google.firebase.messaging.Message; import com.google.firebase.messaging.MulticastMessage; import com.google.firebase.messaging.Notification; @RestController public class FirebasePublisherController { private final FirebaseMessaging fcm; public FirebasePublisherController(FirebaseMessaging fcm) { this.fcm = fcm; } @PostMapping("/topics/{topic}") public ResponseEntity<String> postToTopic(@RequestBody String message, @PathVariable("topic") String topic) throws FirebaseMessagingException { Message msg = Message.builder() .setTopic(topic) .putData("body", message) .build(); String id = fcm.send(msg); return ResponseEntity .status(HttpStatus.ACCEPTED) .body(id); } @PostMapping("/condition") public ResponseEntity<String> postToCondition(@RequestBody ConditionMessageRepresentation message ) throws FirebaseMessagingException { Message msg = Message.builder() .setCondition(message.getCondition()) .putData("body", message.getData()) .build(); String id = fcm.send(msg); return ResponseEntity .status(HttpStatus.ACCEPTED) .body(id); } @PostMapping("/clients/{registrationToken}") public ResponseEntity<String> postToClient(@RequestBody String message, @PathVariable("registrationToken") String registrationToken) throws FirebaseMessagingException { Message msg = Message.builder() .setToken(registrationToken) .putData("body", message) .build(); String id = fcm.send(msg); return ResponseEntity .status(HttpStatus.ACCEPTED) .body(id); } @PostMapping("/clients") public ResponseEntity<List<String>> postToClients(@RequestBody MulticastMessageRepresentation message) throws FirebaseMessagingException { MulticastMessage msg = MulticastMessage.builder() .addAllTokens(message.getRegistrationTokens()) .putData("body", message.getData()) .build(); BatchResponse response = fcm.sendMulticast(msg); List<String> ids = response.getResponses() .stream() .map(r->r.getMessageId()) .collect(Collectors.toList()); return ResponseEntity .status(HttpStatus.ACCEPTED) .body(ids); } @PostMapping("/subscriptions/{topic}") public ResponseEntity<Void> createSubscription(@PathVariable("topic") String topic,@RequestBody List<String> registrationTokens) throws FirebaseMessagingException { fcm.subscribeToTopic(registrationTokens, topic); return ResponseEntity.ok().build(); } @DeleteMapping("/subscriptions/{topic}/{registrationToken}") public ResponseEntity<Void> deleteSubscription(@PathVariable String topic, @PathVariable String registrationToken) throws FirebaseMessagingException { fcm.subscribeToTopic(Arrays.asList(registrationToken), topic); return ResponseEntity.ok().build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/controller/MulticastMessageRepresentation.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/controller/MulticastMessageRepresentation.java
package com.baeldung.gcp.firebase.publisher.controller; import java.util.List; public class MulticastMessageRepresentation { private String data; private List<String> registrationTokens; /** * @return the message */ public String getData() { return data; } /** * @param message the message to set */ public void setData(String data) { this.data = data; } /** * @return the registrationTokens */ public List<String> getRegistrationTokens() { return registrationTokens; } /** * @param registrationTokens the registrationTokens to set */ public void setRegistrationTokens(List<String> registrationTokens) { this.registrationTokens = registrationTokens; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/controller/ConditionMessageRepresentation.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/controller/ConditionMessageRepresentation.java
package com.baeldung.gcp.firebase.publisher.controller; public class ConditionMessageRepresentation { private String condition; private String data; /** * @return the condition */ public String getCondition() { return condition; } /** * @param condition the condition to set */ public void setCondition(String condition) { this.condition = condition; } /** * @return the data */ public String getData() { return data; } /** * @param data the data to set */ public void setData(String data) { this.data = data; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/config/FirebaseProperties.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/config/FirebaseProperties.java
package com.baeldung.gcp.firebase.publisher.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.io.Resource; @ConfigurationProperties(prefix = "gcp.firebase") public class FirebaseProperties { private Resource serviceAccount; /** * @return the serviceAccount */ public Resource getServiceAccount() { return serviceAccount; } /** * @param serviceAccount the serviceAccount to set */ public void setServiceAccount(Resource serviceAccount) { this.serviceAccount = serviceAccount; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/config/FirebaseConfiguration.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/publisher/config/FirebaseConfiguration.java
package com.baeldung.gcp.firebase.publisher.config; import java.io.IOException; import java.io.InputStream; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.api.client.http.HttpTransport; import com.google.auth.oauth2.GoogleCredentials; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.messaging.FirebaseMessaging; @Configuration @EnableConfigurationProperties(FirebaseProperties.class) public class FirebaseConfiguration { private final FirebaseProperties firebaseProperties; public FirebaseConfiguration(FirebaseProperties firebaseProperties) { this.firebaseProperties = firebaseProperties; } @Bean GoogleCredentials googleCredentials() { try { if (firebaseProperties.getServiceAccount() != null) { try( InputStream is = firebaseProperties.getServiceAccount().getInputStream()) { return GoogleCredentials.fromStream(is); } } else { // Use standard credentials chain. Useful when running inside GKE return GoogleCredentials.getApplicationDefault(); } } catch (IOException ioe) { throw new RuntimeException(ioe); } } @Bean FirebaseApp firebaseApp(GoogleCredentials credentials) { FirebaseOptions options = FirebaseOptions.builder() .setCredentials(credentials) .build(); return FirebaseApp.initializeApp(options); } @Bean FirebaseMessaging firebaseMessaging(FirebaseApp firebaseApp) { return FirebaseMessaging.getInstance(firebaseApp); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/firestore/FirestoreConfiguration.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/firestore/FirestoreConfiguration.java
package com.baeldung.gcp.firebase.firestore; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.io.Resource; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.Firestore; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.cloud.FirestoreClient; @Configuration @Profile("!live-test") public class FirestoreConfiguration { @Value("classpath:/private-key.json") private Resource privateKey; @Bean public Firestore firestore() throws IOException { InputStream credentials = new ByteArrayInputStream(privateKey.getContentAsByteArray()); FirebaseOptions firebaseOptions = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(credentials)) .build(); FirebaseApp firebaseApp = FirebaseApp.initializeApp(firebaseOptions); return FirestoreClient.getFirestore(firebaseApp); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/firestore/Task.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/firestore/Task.java
package com.baeldung.gcp.firebase.firestore; import java.util.Date; public class Task { public static final String PATH = "tasks"; private String title; private String description; private String status; private Date dueDate; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/gcp-firebase/src/main/java/com/baeldung/gcp/firebase/firestore/Application.java
gcp-firebase/src/main/java/com/baeldung/gcp/firebase/firestore/Application.java
package com.baeldung.gcp.firebase.firestore; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java
spring-state-machine/src/test/java/com/baeldung/SpringContextTest.java
package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.spring.statemachine.config.ForkJoinStateMachineConfiguration; import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SimpleStateMachineConfiguration.class, SimpleEnumStateMachineConfiguration.class, JunctionStateMachineConfiguration.class, HierarchicalStateMachineConfiguration.class, ForkJoinStateMachineConfiguration.class }) public class SpringContextTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateEnumMachineIntegrationTest.java
spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateEnumMachineIntegrationTest.java
package com.baeldung.spring.statemachine; import com.baeldung.spring.statemachine.applicationreview.ApplicationReviewEvents; import com.baeldung.spring.statemachine.applicationreview.ApplicationReviewStates; import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SimpleEnumStateMachineConfiguration.class) public class StateEnumMachineIntegrationTest { @Autowired private StateMachine<ApplicationReviewStates, ApplicationReviewEvents> stateMachine; @Before public void setUp() { stateMachine.start(); } @Test public void whenStateMachineConfiguredWithEnums_thenStateMachineAcceptsEnumEvents() { assertTrue(stateMachine.sendEvent(ApplicationReviewEvents.APPROVE)); assertEquals(ApplicationReviewStates.PRINCIPAL_REVIEW, stateMachine.getState().getId()); assertTrue(stateMachine.sendEvent(ApplicationReviewEvents.REJECT)); assertEquals(ApplicationReviewStates.REJECTED, stateMachine.getState().getId()); } @After public void tearDown() { stateMachine.stop(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/JunctionStateMachineIntegrationTest.java
spring-state-machine/src/test/java/com/baeldung/spring/statemachine/JunctionStateMachineIntegrationTest.java
package com.baeldung.spring.statemachine; import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = JunctionStateMachineConfiguration.class) public class JunctionStateMachineIntegrationTest { @Autowired private StateMachine<String, String> stateMachine; @Before public void setUp() { stateMachine.start(); } @Test public void whenTransitioningToJunction_thenArriveAtSubJunctionNode() { stateMachine.sendEvent("E1"); Assert.assertEquals("low", stateMachine.getState().getId()); stateMachine.sendEvent("end"); Assert.assertEquals("SF", stateMachine.getState().getId()); } @After public void tearDown() { stateMachine.stop(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/ForkJoinStateMachineIntegrationTest.java
spring-state-machine/src/test/java/com/baeldung/spring/statemachine/ForkJoinStateMachineIntegrationTest.java
package com.baeldung.spring.statemachine; import com.baeldung.spring.statemachine.config.ForkJoinStateMachineConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ForkJoinStateMachineConfiguration.class) public class ForkJoinStateMachineIntegrationTest { @Autowired private StateMachine<String, String> stateMachine; @Before public void setUp() { stateMachine.start(); } @Test public void whenForkStateEntered_thenMultipleSubStatesEntered() { boolean success = stateMachine.sendEvent("E1"); assertTrue(success); assertTrue(Arrays.asList("SFork", "Sub1-1", "Sub2-1").containsAll(stateMachine.getState().getIds())); } @Test public void whenAllConfiguredJoinEntryStatesAreEntered_thenTransitionToJoinState() { boolean success = stateMachine.sendEvent("E1"); assertTrue(success); assertTrue(Arrays.asList("SFork", "Sub1-1", "Sub2-1").containsAll(stateMachine.getState().getIds())); assertTrue(stateMachine.sendEvent("sub1")); assertTrue(stateMachine.sendEvent("sub2")); assertEquals("SJoin", stateMachine.getState().getId()); } @After public void tearDown() { stateMachine.stop(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineBuilderIntegrationTest.java
spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineBuilderIntegrationTest.java
package com.baeldung.spring.statemachine; import org.junit.Test; import org.springframework.statemachine.StateMachine; import org.springframework.statemachine.config.StateMachineBuilder; import static org.junit.Assert.assertEquals; public class StateMachineBuilderIntegrationTest { @Test public void whenUseStateMachineBuilder_thenBuildSuccessAndMachineWorks() throws Exception { StateMachineBuilder.Builder<String, String> builder = StateMachineBuilder.builder(); builder.configureStates().withStates() .initial("SI") .state("S1") .end("SF"); builder.configureTransitions() .withExternal() .source("SI").target("S1").event("E1") .and().withExternal() .source("S1").target("SF").event("E2"); StateMachine machine = builder.build(); machine.start(); machine.sendEvent("E1"); assertEquals("S1", machine.getState().getId()); machine.sendEvent("E2"); assertEquals("SF", machine.getState().getId()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/HierarchicalStateMachineIntegrationTest.java
spring-state-machine/src/test/java/com/baeldung/spring/statemachine/HierarchicalStateMachineIntegrationTest.java
package com.baeldung.spring.statemachine; import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Arrays; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = HierarchicalStateMachineConfiguration.class) public class HierarchicalStateMachineIntegrationTest { @Autowired private StateMachine<String, String> stateMachine; @Before public void setUp() { stateMachine.start(); } @Test public void whenTransitionToSubMachine_thenSubStateIsEntered() { assertEquals(Arrays.asList("SI", "SUB1"), stateMachine.getState().getIds()); stateMachine.sendEvent("se1"); assertEquals(Arrays.asList("SI", "SUB2"), stateMachine.getState().getIds()); stateMachine.sendEvent("s-end"); assertEquals(Arrays.asList("SI", "SUBEND"), stateMachine.getState().getIds()); stateMachine.sendEvent("end"); assertEquals(1, stateMachine.getState().getIds().size()); assertEquals("SF", stateMachine.getState().getId()); } @After public void tearDown() { stateMachine.stop(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java
spring-state-machine/src/test/java/com/baeldung/spring/statemachine/StateMachineIntegrationTest.java
package com.baeldung.spring.statemachine; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.statemachine.StateMachine; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SimpleStateMachineConfiguration.class) @TestMethodOrder(OrderAnnotation.class) public class StateMachineIntegrationTest { @Autowired private StateMachine<String, String> stateMachine; @BeforeEach public void setUp() { stateMachine.start(); } @Test @Order(1) public void whenSimpleStringStateMachineEvents_thenEndState() { assertEquals("SI", stateMachine.getState().getId()); stateMachine.sendEvent("E1"); assertEquals("S1", stateMachine.getState().getId()); stateMachine.sendEvent("E2"); assertEquals("S2", stateMachine.getState().getId()); } @Test @Order(2) public void whenSimpleStringMachineActionState_thenActionExecuted() { stateMachine.sendEvent("E3"); assertEquals("S3", stateMachine.getState().getId()); boolean acceptedE4 = stateMachine.sendEvent("E4"); assertTrue(acceptedE4); assertEquals("S4", stateMachine.getState().getId()); stateMachine.sendEvent("E5"); assertEquals("S5", stateMachine.getState().getId()); stateMachine.sendEvent("end"); assertEquals("SF", stateMachine.getState().getId()); assertEquals(2, stateMachine.getExtendedState().getVariables().get("approvalCount")); } @AfterEach public void tearDown() { stateMachine.stop(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/applicationreview/ApplicationReviewEvents.java
spring-state-machine/src/main/java/com/baeldung/spring/statemachine/applicationreview/ApplicationReviewEvents.java
package com.baeldung.spring.statemachine.applicationreview; public enum ApplicationReviewEvents { APPROVE, REJECT }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/applicationreview/ApplicationReviewStates.java
spring-state-machine/src/main/java/com/baeldung/spring/statemachine/applicationreview/ApplicationReviewStates.java
package com.baeldung.spring.statemachine.applicationreview; public enum ApplicationReviewStates { PEER_REVIEW, PRINCIPAL_REVIEW, APPROVED, REJECTED }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/SimpleEnumStateMachineConfiguration.java
spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/SimpleEnumStateMachineConfiguration.java
package com.baeldung.spring.statemachine.config; import com.baeldung.spring.statemachine.applicationreview.ApplicationReviewEvents; import com.baeldung.spring.statemachine.applicationreview.ApplicationReviewStates; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.config.EnableStateMachine; import org.springframework.statemachine.config.StateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; @Configuration @EnableStateMachine public class SimpleEnumStateMachineConfiguration extends StateMachineConfigurerAdapter<ApplicationReviewStates, ApplicationReviewEvents> { @Override public void configure(StateMachineConfigurationConfigurer<ApplicationReviewStates, ApplicationReviewEvents> config) throws Exception { config .withConfiguration() .autoStartup(true) .listener(new StateMachineListener()); } @Override public void configure(StateMachineStateConfigurer<ApplicationReviewStates, ApplicationReviewEvents> states) throws Exception { states .withStates() .initial(ApplicationReviewStates.PEER_REVIEW) .state(ApplicationReviewStates.PRINCIPAL_REVIEW) .end(ApplicationReviewStates.APPROVED) .end(ApplicationReviewStates.REJECTED); } @Override public void configure(StateMachineTransitionConfigurer<ApplicationReviewStates, ApplicationReviewEvents> transitions) throws Exception { transitions.withExternal() .source(ApplicationReviewStates.PEER_REVIEW).target(ApplicationReviewStates.PRINCIPAL_REVIEW).event(ApplicationReviewEvents.APPROVE) .and().withExternal() .source(ApplicationReviewStates.PRINCIPAL_REVIEW).target(ApplicationReviewStates.APPROVED).event(ApplicationReviewEvents.APPROVE) .and().withExternal() .source(ApplicationReviewStates.PEER_REVIEW).target(ApplicationReviewStates.REJECTED).event(ApplicationReviewEvents.REJECT) .and().withExternal() .source(ApplicationReviewStates.PRINCIPAL_REVIEW).target(ApplicationReviewStates.REJECTED).event(ApplicationReviewEvents.REJECT); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/StateMachineListener.java
spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/StateMachineListener.java
package com.baeldung.spring.statemachine.config; import org.springframework.statemachine.listener.StateMachineListenerAdapter; import org.springframework.statemachine.state.State; import java.util.logging.Logger; public class StateMachineListener extends StateMachineListenerAdapter { private static final Logger LOGGER = Logger.getLogger(StateMachineListener.class.getName()); @Override public void stateChanged(State from, State to) { LOGGER.info(() -> String.format("Transitioned from %s to %s%n", from == null ? "none" : from.getId(), to.getId())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/SimpleStateMachineConfiguration.java
spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/SimpleStateMachineConfiguration.java
package com.baeldung.spring.statemachine.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.action.Action; import org.springframework.statemachine.config.EnableStateMachine; import org.springframework.statemachine.config.StateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; import org.springframework.statemachine.guard.Guard; import java.util.Arrays; import java.util.HashSet; import java.util.logging.Logger; @Configuration @EnableStateMachine public class SimpleStateMachineConfiguration extends StateMachineConfigurerAdapter<String, String> { private static final Logger LOGGER = Logger.getLogger(SimpleStateMachineConfiguration.class.getName()); @Override public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception { config .withConfiguration() .autoStartup(true) .listener(new StateMachineListener()); } @Override public void configure(StateMachineStateConfigurer<String, String> states) throws Exception { states .withStates() .initial("SI") .end("SF") .states(new HashSet<>(Arrays.asList("S1", "S2"))) .stateEntry("S3", entryAction()) .stateExit("S3", exitAction()) .state("S4", executeAction(), errorAction()) .state("S5", executeAction(), errorAction()); } @Override public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception { transitions .withExternal() .source("SI") .target("S1") .event("E1") .action(initAction()) .and() .withExternal() .source("S1") .target("S2") .event("E2") .and() .withExternal() .source("SI") .target("S3") .event("E3") .and() .withExternal() .source("S3") .target("S4") .event("E4") .and() .withExternal() .source("S4") .target("S5") .event("E5") .and() .withExternal() .source("S5") .target("SF") .event("end") .guard(simpleGuard()); } @Bean public Guard<String, String> simpleGuard() { return ctx -> { int approvalCount = (int) ctx .getExtendedState() .getVariables() .getOrDefault("approvalCount", 0); return approvalCount > 0; }; } @Bean public Action<String, String> entryAction() { return ctx -> LOGGER.info("Entry " + ctx .getTarget() .getId()); } @Bean public Action<String, String> doAction() { return ctx -> LOGGER.info("Do " + ctx .getTarget() .getId()); } @Bean public Action<String, String> executeAction() { return ctx -> { LOGGER.info("Execute " + ctx .getTarget() .getId()); int approvals = (int) ctx .getExtendedState() .getVariables() .getOrDefault("approvalCount", 0); approvals++; ctx .getExtendedState() .getVariables() .put("approvalCount", approvals); }; } @Bean public Action<String, String> exitAction() { return ctx -> LOGGER.info("Exit " + ctx .getSource() .getId() + " -> " + ctx .getTarget() .getId()); } @Bean public Action<String, String> errorAction() { return ctx -> LOGGER.info("Error " + ctx .getSource() .getId() + ctx.getException()); } @Bean public Action<String, String> initAction() { return ctx -> LOGGER.info(ctx .getTarget() .getId()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/ForkJoinStateMachineConfiguration.java
spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/ForkJoinStateMachineConfiguration.java
package com.baeldung.spring.statemachine.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.config.EnableStateMachine; import org.springframework.statemachine.config.StateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; import org.springframework.statemachine.guard.Guard; @Configuration @EnableStateMachine public class ForkJoinStateMachineConfiguration extends StateMachineConfigurerAdapter<String, String> { @Override public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception { config .withConfiguration() .autoStartup(true) .listener(new StateMachineListener()); } @Override public void configure(StateMachineStateConfigurer<String, String> states) throws Exception { states .withStates() .initial("SI") .fork("SFork") .join("SJoin") .end("SF") .and() .withStates() .parent("SFork") .initial("Sub1-1") .end("Sub1-2") .and() .withStates() .parent("SFork") .initial("Sub2-1") .end("Sub2-2"); } @Override public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception { transitions.withExternal() .source("SI").target("SFork").event("E1") .and().withExternal() .source("Sub1-1").target("Sub1-2").event("sub1") .and().withExternal() .source("Sub2-1").target("Sub2-2").event("sub2") .and() .withFork() .source("SFork") .target("Sub1-1") .target("Sub2-1") .and() .withJoin() .source("Sub1-2") .source("Sub2-2") .target("SJoin"); } @Bean public Guard<String, String> mediumGuard() { return ctx -> false; } @Bean public Guard<String, String> highGuard() { return ctx -> false; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/JunctionStateMachineConfiguration.java
spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/JunctionStateMachineConfiguration.java
package com.baeldung.spring.statemachine.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.config.EnableStateMachine; import org.springframework.statemachine.config.StateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; import org.springframework.statemachine.guard.Guard; @Configuration @EnableStateMachine public class JunctionStateMachineConfiguration extends StateMachineConfigurerAdapter<String, String> { @Override public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception { config .withConfiguration() .autoStartup(true) .listener(new StateMachineListener()); } @Override public void configure(StateMachineStateConfigurer<String, String> states) throws Exception { states .withStates() .initial("SI") .junction("SJ") .state("high") .state("medium") .state("low") .end("SF"); } @Override public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception { transitions.withExternal() .source("SI").target("SJ").event("E1") .and() .withJunction() .source("SJ") .first("high", highGuard()) .then("medium", mediumGuard()) .last("low") .and().withExternal() .source("low").target("SF").event("end"); } @Bean public Guard<String, String> mediumGuard() { return ctx -> false; } @Bean public Guard<String, String> highGuard() { return ctx -> false; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/HierarchicalStateMachineConfiguration.java
spring-state-machine/src/main/java/com/baeldung/spring/statemachine/config/HierarchicalStateMachineConfiguration.java
package com.baeldung.spring.statemachine.config; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.config.EnableStateMachine; import org.springframework.statemachine.config.StateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; @Configuration @EnableStateMachine public class HierarchicalStateMachineConfiguration extends StateMachineConfigurerAdapter<String, String> { @Override public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception { config .withConfiguration() .autoStartup(true) .listener(new StateMachineListener()); } @Override public void configure(StateMachineStateConfigurer<String, String> states) throws Exception { states .withStates() .initial("SI") .state("SI") .end("SF") .and() .withStates() .parent("SI") .initial("SUB1") .state("SUB2") .end("SUBEND"); } @Override public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception { transitions.withExternal() .source("SI").target("SF").event("end") .and().withExternal() .source("SUB1").target("SUB2").event("se1") .and().withExternal() .source("SUB2").target("SUBEND").event("s-end"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/service/MailServiceIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/service/MailServiceIntTest.java
package com.baeldung.jhipster.uaa.service; import com.baeldung.jhipster.uaa.config.Constants; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.domain.User; import io.github.jhipster.config.JHipsterProperties; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.MessageSource; import org.springframework.mail.MailSendException; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.test.context.junit4.SpringRunner; import org.thymeleaf.spring5.SpringTemplateEngine; import javax.mail.Multipart; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.ByteArrayOutputStream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) public class MailServiceIntTest { @Autowired private JHipsterProperties jHipsterProperties; @Autowired private MessageSource messageSource; @Autowired private SpringTemplateEngine templateEngine; @Spy private JavaMailSenderImpl javaMailSender; @Captor private ArgumentCaptor<MimeMessage> messageCaptor; private MailService mailService; @Before public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(javaMailSender).send(any(MimeMessage.class)); mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine); } @Test public 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].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent().toString()).isEqualTo("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); } @Test public 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].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent().toString()).isEqualTo("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public 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].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos.toString()).isEqualTo("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); } @Test public 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].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos.toString()).isEqualTo("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendEmailFromTemplate() throws Exception { User user = new User(); user.setLogin("john"); user.setEmail("john.doe@example.com"); user.setLangKey("en"); 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].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); 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 public 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].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public 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].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public 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].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendEmailWithException() throws Exception { doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/service/UserServiceIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/service/UserServiceIntTest.java
package com.baeldung.jhipster.uaa.service; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.config.Constants; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.repository.UserRepository; import com.baeldung.jhipster.uaa.service.dto.UserDTO; import com.baeldung.jhipster.uaa.service.util.RandomUtil; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.auditing.AuditingHandler; import org.springframework.data.auditing.DateTimeProvider; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.time.LocalDateTime; import java.util.Optional; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; /** * Test class for the UserResource REST controller. * * @see UserService */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) @Transactional public class UserServiceIntTest { @Autowired private UserRepository userRepository; @Autowired private UserService userService; @Autowired private AuditingHandler auditingHandler; @Mock DateTimeProvider dateTimeProvider; private User user; @Before public void init() { user = new User(); user.setLogin("johndoe"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setEmail("johndoe@localhost"); user.setFirstName("john"); user.setLastName("doe"); user.setImageUrl("http://placehold.it/50x50"); user.setLangKey("en"); when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now())); auditingHandler.setDateTimeProvider(dateTimeProvider); } @Test @Transactional public 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 public void assertThatOnlyActivatedUserCanRequestPasswordReset() { user.setActivated(false); userRepository.saveAndFlush(user); Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin()); assertThat(maybeUser).isNotPresent(); userRepository.delete(user); } @Test @Transactional public 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 public 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 public 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 public void testFindNotActivatedUsersByCreationDateBefore() { 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); List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); assertThat(users).isNotEmpty(); userService.removeNotActivatedUsers(); users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); assertThat(users).isEmpty(); } @Test @Transactional public void assertThatAnonymousUserIsNotGet() { user.setLogin(Constants.ANONYMOUS_USER); if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) { userRepository.saveAndFlush(user); } final PageRequest pageable = PageRequest.of(0, (int) userRepository.count()); final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable); assertThat(allManagedUsers.getContent().stream() .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) .isTrue(); } @Test @Transactional public void testRemoveNotActivatedUsers() { // custom "now" for audit to use as creation date when(dateTimeProvider.getNow()).thenReturn(Optional.of(Instant.now().minus(30, ChronoUnit.DAYS))); user.setActivated(false); userRepository.saveAndFlush(user); assertThat(userRepository.findOneByLogin("johndoe")).isPresent(); userService.removeNotActivatedUsers(); assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/repository/CustomAuditEventRepositoryIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/repository/CustomAuditEventRepositoryIntTest.java
package com.baeldung.jhipster.uaa.repository; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.config.Constants; import com.baeldung.jhipster.uaa.config.audit.AuditEventConverter; import com.baeldung.jhipster.uaa.domain.PersistentAuditEvent; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpSession; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static com.baeldung.jhipster.uaa.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; /** * Test class for the CustomAuditEventRepository class. * * @see CustomAuditEventRepository */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) @Transactional public class CustomAuditEventRepositoryIntTest { @Autowired private PersistenceAuditEventRepository persistenceAuditEventRepository; @Autowired private AuditEventConverter auditEventConverter; private CustomAuditEventRepository customAuditEventRepository; private PersistentAuditEvent testUserEvent; private PersistentAuditEvent testOtherUserEvent; private PersistentAuditEvent testOldUserEvent; @Before public void setup() { customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter); persistenceAuditEventRepository.deleteAll(); Instant oneHourAgo = Instant.now().minusSeconds(3600); testUserEvent = new PersistentAuditEvent(); testUserEvent.setPrincipal("test-user"); testUserEvent.setAuditEventType("test-type"); testUserEvent.setAuditEventDate(oneHourAgo); Map<String, String> data = new HashMap<>(); data.put("test-key", "test-value"); testUserEvent.setData(data); testOldUserEvent = new PersistentAuditEvent(); testOldUserEvent.setPrincipal("test-user"); testOldUserEvent.setAuditEventType("test-type"); testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000)); testOtherUserEvent = new PersistentAuditEvent(); testOtherUserEvent.setPrincipal("other-test-user"); testOtherUserEvent.setAuditEventType("test-type"); testOtherUserEvent.setAuditEventDate(oneHourAgo); } @Test public void addAuditEvent() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); assertThat(persistentAuditEvent.getData()).containsKey("test-key"); assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value"); assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp()); } @Test public void addAuditEventTruncateLargeData() { Map<String, Object> data = new HashMap<>(); StringBuilder largeData = new StringBuilder(); for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { largeData.append("a"); } data.put("test-key", largeData); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); assertThat(persistentAuditEvent.getData()).containsKey("test-key"); String actualData = persistentAuditEvent.getData().get("test-key"); assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH); assertThat(actualData).isSubstringOf(largeData); assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp()); } @Test public void testAddEventWithWebAuthenticationDetails() { HttpSession session = new MockHttpSession(null, "test-session-id"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); request.setRemoteAddr("1.2.3.4"); WebAuthenticationDetails details = new WebAuthenticationDetails(request); Map<String, Object> data = new HashMap<>(); data.put("test-key", details); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); } @Test public void testAddEventWithNullData() { Map<String, Object> data = new HashMap<>(); data.put("test-key", null); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null"); } @Test public void addAuditEventWithAnonymousUser() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(0); } @Test public void addAuditEventWithAuthorizationFailureType() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(0); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/security/DomainUserDetailsServiceIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/security/DomainUserDetailsServiceIntTest.java
package com.baeldung.jhipster.uaa.security; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.repository.UserRepository; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.Locale; import static org.assertj.core.api.Assertions.assertThat; /** * Test class for DomainUserDetailsService. * * @see DomainUserDetailsService */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) @Transactional public class DomainUserDetailsServiceIntTest { 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 private UserDetailsService domainUserDetailsService; private User userOne; private User userTwo; private User userThree; @Before public void init() { userOne = new User(); userOne.setLogin(USER_ONE_LOGIN); userOne.setPassword(RandomStringUtils.random(60)); userOne.setActivated(true); userOne.setEmail(USER_ONE_EMAIL); userOne.setFirstName("userOne"); userOne.setLastName("doe"); userOne.setLangKey("en"); userRepository.save(userOne); userTwo = new User(); userTwo.setLogin(USER_TWO_LOGIN); userTwo.setPassword(RandomStringUtils.random(60)); userTwo.setActivated(true); userTwo.setEmail(USER_TWO_EMAIL); userTwo.setFirstName("userTwo"); userTwo.setLastName("doe"); userTwo.setLangKey("en"); userRepository.save(userTwo); userThree = new User(); userThree.setLogin(USER_THREE_LOGIN); userThree.setPassword(RandomStringUtils.random(60)); userThree.setActivated(false); userThree.setEmail(USER_THREE_EMAIL); userThree.setFirstName("userThree"); userThree.setLastName("doe"); userThree.setLangKey("en"); userRepository.save(userThree); } @Test @Transactional public void assertThatUserCanBeFoundByLogin() { UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN); assertThat(userDetails).isNotNull(); assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); } @Test @Transactional public void assertThatUserCanBeFoundByLoginIgnoreCase() { UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH)); assertThat(userDetails).isNotNull(); assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); } @Test @Transactional public void assertThatUserCanBeFoundByEmail() { UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL); assertThat(userDetails).isNotNull(); assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); } @Test(expected = UsernameNotFoundException.class) @Transactional public void assertThatUserCanNotBeFoundByEmailIgnoreCase() { domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)); } @Test @Transactional public void assertThatEmailIsPrioritizedOverLogin() { UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL); assertThat(userDetails).isNotNull(); assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); } @Test(expected = UserNotActivatedException.class) @Transactional public void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() { 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-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/security/OAuth2TokenMockUtil.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/security/OAuth2TokenMockUtil.java
package com.baeldung.jhipster.uaa.security; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; import org.springframework.stereotype.Component; import org.springframework.test.web.servlet.request.RequestPostProcessor; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import static org.mockito.BDDMockito.given; /** * A bean providing simple mocking of OAuth2 access tokens for security integration tests. */ @Component public class OAuth2TokenMockUtil { @MockBean private ResourceServerTokenServices tokenServices; private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) { List<GrantedAuthority> authorities = roles.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(username, "test", true, true, true, true, authorities); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); // Create the authorization request and OAuth2Authentication object OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null, null); return new OAuth2Authentication(authRequest, authentication); } public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes, Set<String> roles) { String uuid = String.valueOf(UUID.randomUUID()); given(tokenServices.loadAuthentication(uuid)) .willReturn(createAuthentication(username, scopes, roles)); given(tokenServices.readAccessToken(uuid)).willReturn(new DefaultOAuth2AccessToken(uuid)); return new OAuth2PostProcessor(uuid); } public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes) { return oauth2Authentication(username, scopes, Collections.emptySet()); } public RequestPostProcessor oauth2Authentication(String username) { return oauth2Authentication(username, Collections.emptySet()); } public static class OAuth2PostProcessor implements RequestPostProcessor { private String token; public OAuth2PostProcessor(String token) { this.token = token; } @Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest mockHttpServletRequest) { mockHttpServletRequest.addHeader("Authorization", "Bearer " + token); return mockHttpServletRequest; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/security/SecurityUtilsUnitTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/security/SecurityUtilsUnitTest.java
package com.baeldung.jhipster.uaa.security; import org.junit.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; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; /** * Test class for the SecurityUtils utility class. * * @see SecurityUtils */ public class SecurityUtilsUnitTest { @Test public 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 public void testIsAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isTrue(); } @Test public 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 public void testIsCurrentUserInRole() { 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.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue(); assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/config/WebConfigurerUnitTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/config/WebConfigurerUnitTest.java
package com.baeldung.jhipster.uaa.config; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.servlet.InstrumentedFilter; import com.codahale.metrics.servlets.MetricsServlet; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.undertow.Undertow; import io.undertow.Undertow.Builder; import io.undertow.UndertowOptions; import org.h2.server.web.WebServlet; import org.junit.Before; import org.junit.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.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.xnio.OptionMap; import javax.servlet.*; import java.util.*; 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; /** * Unit tests for the WebConfigurer class. * * @see WebConfigurer */ public class WebConfigurerUnitTest { private WebConfigurer webConfigurer; private MockServletContext servletContext; private MockEnvironment env; private JHipsterProperties props; private MetricRegistry metricRegistry; @Before 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); metricRegistry = new MetricRegistry(); webConfigurer.setMetricRegistry(metricRegistry); } @Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); } @Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); } @Test public void testCustomizeServletContainer() { 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;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); } @Test public void testUndertowHttp2Enabled() { props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); } @Test public void testCorsFilterOnApiPath() 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( 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 public void testCorsFilterOnOtherPath() 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 public void testCorsFilterDeactivated() 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 public void testCorsFilterDeactivated2() 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-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/config/SecurityBeanOverrideConfiguration.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/config/SecurityBeanOverrideConfiguration.java
package com.baeldung.jhipster.uaa.config; import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.web.client.RestTemplate; /** * Overrides UAA specific beans, so they do not interfere the testing * This configuration must be included in @SpringBootTest in order to take effect. */ @Configuration public class SecurityBeanOverrideConfiguration { @Bean @Primary public TokenStore tokenStore() { return null; } @Bean @Primary public JwtAccessTokenConverter jwtAccessTokenConverter() { return null; } @Bean @Primary public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) { return null; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/config/WebConfigurerTestController.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/config/WebConfigurerTestController.java
package com.baeldung.jhipster.uaa.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-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/AuditResourceIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/AuditResourceIntTest.java
package com.baeldung.jhipster.uaa.web.rest; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.config.audit.AuditEventConverter; import com.baeldung.jhipster.uaa.domain.PersistentAuditEvent; import com.baeldung.jhipster.uaa.repository.PersistenceAuditEventRepository; import com.baeldung.jhipster.uaa.service.AuditEventService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.format.support.FormattingConversionService; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the AuditResource REST controller. * * @see AuditResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) @Transactional public class AuditResourceIntTest { private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL"; private static final String SAMPLE_TYPE = "SAMPLE_TYPE"; private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z"); private static final long SECONDS_PER_DAY = 60 * 60 * 24; @Autowired private PersistenceAuditEventRepository auditEventRepository; @Autowired private AuditEventConverter auditEventConverter; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private FormattingConversionService formattingConversionService; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; private PersistentAuditEvent auditEvent; private MockMvc restAuditMockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); AuditEventService auditEventService = new AuditEventService(auditEventRepository, auditEventConverter); AuditResource auditResource = new AuditResource(auditEventService); this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setConversionService(formattingConversionService) .setMessageConverters(jacksonMessageConverter).build(); } @Before public void initTest() { auditEventRepository.deleteAll(); auditEvent = new PersistentAuditEvent(); auditEvent.setAuditEventType(SAMPLE_TYPE); auditEvent.setPrincipal(SAMPLE_PRINCIPAL); auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP); } @Test public void getAllAudits() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Get all the audits restAuditMockMvc.perform(get("/management/audits")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); } @Test public void getAudit() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Get the audit restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); } @Test public void getAuditsByDate() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Generate dates for selecting audits by date, making sure the period will contain the audit String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); // Get the audit restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); } @Test public void getNonExistingAuditsByDate() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Generate dates for selecting audits by date, making sure the period will not contain the sample audit String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10); String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); // Query audits but expect no results restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(header().string("X-Total-Count", "0")); } @Test public void getNonExistingAudit() throws Exception { // Get the audit restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/TestUtil.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/TestUtil.java
package com.baeldung.jhipster.uaa.web.rest; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionService; import org.springframework.http.MediaType; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; import java.time.format.DateTimeParseException; import static org.assertj.core.api.Assertions.assertThat; /** * Utility class for testing REST controllers. */ public class TestUtil { /** MediaType for JSON UTF8 */ public static final MediaType APPLICATION_JSON_UTF8 = new MediaType( MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8); /** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); } /** * 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 reprensents 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); } /** * 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.hashCode()).isEqualTo(domainObject1.hashCode()); // 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.hashCode()).isEqualTo(domainObject2.hashCode()); } /** * Create a FormattingConversionService which use ISO date format, instead of the localized one. * @return the FormattingConversionService */ public static FormattingConversionService createFormattingConversionService() { DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService (); DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(dfcs); return dfcs; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/UserResourceIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/UserResourceIntTest.java
package com.baeldung.jhipster.uaa.web.rest; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.domain.Authority; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.repository.UserRepository; import com.baeldung.jhipster.uaa.security.AuthoritiesConstants; import com.baeldung.jhipster.uaa.service.MailService; import com.baeldung.jhipster.uaa.service.UserService; import com.baeldung.jhipster.uaa.service.dto.UserDTO; import com.baeldung.jhipster.uaa.service.mapper.UserMapper; import com.baeldung.jhipster.uaa.web.rest.errors.ExceptionTranslator; import com.baeldung.jhipster.uaa.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cache.CacheManager; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.time.Instant; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the UserResource REST controller. * * @see UserResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) public class UserResourceIntTest { 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 UserRepository userRepository; @Autowired private MailService mailService; @Autowired private UserService userService; @Autowired private UserMapper userMapper; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; @Autowired private CacheManager cacheManager; private MockMvc restUserMockMvc; private User user; @Before public void setup() { cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).clear(); cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE).clear(); UserResource userResource = new UserResource(userService, userRepository, mailService); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setMessageConverters(jacksonMessageConverter) .build(); } /** * 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.random(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; } @Before public void initTest() { user = createEntity(em); user.setLogin(DEFAULT_LOGIN); user.setEmail(DEFAULT_EMAIL); } @Test @Transactional public void createUser() throws Exception { int databaseSizeBeforeCreate = userRepository.findAll().size(); // Create the User ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setLogin(DEFAULT_LOGIN); managedUserVM.setPassword(DEFAULT_PASSWORD); managedUserVM.setFirstName(DEFAULT_FIRSTNAME); managedUserVM.setLastName(DEFAULT_LASTNAME); managedUserVM.setEmail(DEFAULT_EMAIL); managedUserVM.setActivated(true); managedUserVM.setImageUrl(DEFAULT_IMAGEURL); managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isCreated()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate + 1); User testUser = userList.get(userList.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 public void createUserWithExistingId() throws Exception { int databaseSizeBeforeCreate = userRepository.findAll().size(); ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setId(1L); managedUserVM.setLogin(DEFAULT_LOGIN); managedUserVM.setPassword(DEFAULT_PASSWORD); managedUserVM.setFirstName(DEFAULT_FIRSTNAME); managedUserVM.setLastName(DEFAULT_LASTNAME); managedUserVM.setEmail(DEFAULT_EMAIL); managedUserVM.setActivated(true); managedUserVM.setImageUrl(DEFAULT_IMAGEURL); managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // An entity with an existing ID cannot be created, so this API call must fail restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void createUserWithExistingLogin() throws Exception { // Initialize the database userRepository.saveAndFlush(user); int databaseSizeBeforeCreate = userRepository.findAll().size(); ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used managedUserVM.setPassword(DEFAULT_PASSWORD); managedUserVM.setFirstName(DEFAULT_FIRSTNAME); managedUserVM.setLastName(DEFAULT_LASTNAME); managedUserVM.setEmail("anothermail@localhost"); managedUserVM.setActivated(true); managedUserVM.setImageUrl(DEFAULT_IMAGEURL); managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void createUserWithExistingEmail() throws Exception { // Initialize the database userRepository.saveAndFlush(user); int databaseSizeBeforeCreate = userRepository.findAll().size(); ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setLogin("anotherlogin"); managedUserVM.setPassword(DEFAULT_PASSWORD); managedUserVM.setFirstName(DEFAULT_FIRSTNAME); managedUserVM.setLastName(DEFAULT_LASTNAME); managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used managedUserVM.setActivated(true); managedUserVM.setImageUrl(DEFAULT_IMAGEURL); managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllUsers() 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_UTF8_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 public void getUser() throws Exception { // Initialize the database userRepository.saveAndFlush(user); assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull(); // Get the user restUserMockMvc.perform(get("/api/users/{login}", user.getLogin())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_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)); assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNotNull(); } @Test @Transactional public void getNonExistingUser() throws Exception { restUserMockMvc.perform(get("/api/users/unknown")) .andExpect(status().isNotFound()); } @Test @Transactional public void updateUser() throws Exception { // Initialize the database userRepository.saveAndFlush(user); int databaseSizeBeforeUpdate = userRepository.findAll().size(); // Update the user User updatedUser = userRepository.findById(user.getId()).get(); ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setId(updatedUser.getId()); managedUserVM.setLogin(updatedUser.getLogin()); managedUserVM.setPassword(UPDATED_PASSWORD); managedUserVM.setFirstName(UPDATED_FIRSTNAME); managedUserVM.setLastName(UPDATED_LASTNAME); managedUserVM.setEmail(UPDATED_EMAIL); managedUserVM.setActivated(updatedUser.getActivated()); managedUserVM.setImageUrl(UPDATED_IMAGEURL); managedUserVM.setLangKey(UPDATED_LANGKEY); managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform(put("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isOk()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeUpdate); User testUser = userList.get(userList.size() - 1); 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 public void updateUserLogin() throws Exception { // Initialize the database userRepository.saveAndFlush(user); int databaseSizeBeforeUpdate = userRepository.findAll().size(); // Update the user User updatedUser = userRepository.findById(user.getId()).get(); ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setId(updatedUser.getId()); managedUserVM.setLogin(UPDATED_LOGIN); managedUserVM.setPassword(UPDATED_PASSWORD); managedUserVM.setFirstName(UPDATED_FIRSTNAME); managedUserVM.setLastName(UPDATED_LASTNAME); managedUserVM.setEmail(UPDATED_EMAIL); managedUserVM.setActivated(updatedUser.getActivated()); managedUserVM.setImageUrl(UPDATED_IMAGEURL); managedUserVM.setLangKey(UPDATED_LANGKEY); managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform(put("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isOk()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeUpdate); User testUser = userList.get(userList.size() - 1); 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 public void updateUserExistingEmail() throws Exception { // Initialize the database with 2 users userRepository.saveAndFlush(user); User anotherUser = new User(); anotherUser.setLogin("jhipster"); anotherUser.setPassword(RandomStringUtils.random(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()).get(); ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setId(updatedUser.getId()); managedUserVM.setLogin(updatedUser.getLogin()); managedUserVM.setPassword(updatedUser.getPassword()); managedUserVM.setFirstName(updatedUser.getFirstName()); managedUserVM.setLastName(updatedUser.getLastName()); managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser managedUserVM.setActivated(updatedUser.getActivated()); managedUserVM.setImageUrl(updatedUser.getImageUrl()); managedUserVM.setLangKey(updatedUser.getLangKey()); managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform(put("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); } @Test @Transactional public void updateUserExistingLogin() throws Exception { // Initialize the database userRepository.saveAndFlush(user); User anotherUser = new User(); anotherUser.setLogin("jhipster"); anotherUser.setPassword(RandomStringUtils.random(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()).get(); ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setId(updatedUser.getId()); managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser managedUserVM.setPassword(updatedUser.getPassword()); managedUserVM.setFirstName(updatedUser.getFirstName()); managedUserVM.setLastName(updatedUser.getLastName()); managedUserVM.setEmail(updatedUser.getEmail()); managedUserVM.setActivated(updatedUser.getActivated()); managedUserVM.setImageUrl(updatedUser.getImageUrl()); managedUserVM.setLangKey(updatedUser.getLangKey()); managedUserVM.setCreatedBy(updatedUser.getCreatedBy()); managedUserVM.setCreatedDate(updatedUser.getCreatedDate()); managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy()); managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform(put("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); } @Test @Transactional public void deleteUser() throws Exception { // Initialize the database userRepository.saveAndFlush(user); int databaseSizeBeforeDelete = userRepository.findAll().size(); // Delete the user restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull(); // Validate the database is empty List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void getAllAuthorities() throws Exception { restUserMockMvc.perform(get("/api/users/authorities") .accept(TestUtil.APPLICATION_JSON_UTF8) .contentType(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$").isArray()) .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); } @Test @Transactional public void testUserEquals() throws Exception { TestUtil.equalsVerifier(User.class); User user1 = new User(); user1.setId(1L); 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 public void testUserFromId() { assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID); assertThat(userMapper.userFromId(null)).isNull(); } @Test public void testUserDTOtoUser() { UserDTO userDTO = new UserDTO(); 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.getActivated()).isEqualTo(true); 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 public 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); UserDTO userDTO = userMapper.userToUserDTO(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()).isEqualTo(true); 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(); } @Test public void testAuthorityEquals() { Authority authorityA = new Authority(); assertThat(authorityA).isEqualTo(authorityA); assertThat(authorityA).isNotEqualTo(null); assertThat(authorityA).isNotEqualTo(new Object()); assertThat(authorityA.hashCode()).isEqualTo(0); assertThat(authorityA.toString()).isNotNull(); Authority authorityB = new Authority(); assertThat(authorityA).isEqualTo(authorityB); authorityB.setName(AuthoritiesConstants.ADMIN); assertThat(authorityA).isNotEqualTo(authorityB); authorityA.setName(AuthoritiesConstants.USER); assertThat(authorityA).isNotEqualTo(authorityB); authorityB.setName(AuthoritiesConstants.USER); assertThat(authorityA).isEqualTo(authorityB); assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/AccountResourceIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/AccountResourceIntTest.java
package com.baeldung.jhipster.uaa.web.rest; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.config.Constants; import com.baeldung.jhipster.uaa.domain.Authority; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.repository.AuthorityRepository; import com.baeldung.jhipster.uaa.repository.UserRepository; import com.baeldung.jhipster.uaa.security.AuthoritiesConstants; import com.baeldung.jhipster.uaa.service.MailService; import com.baeldung.jhipster.uaa.service.UserService; import com.baeldung.jhipster.uaa.service.dto.PasswordChangeDTO; import com.baeldung.jhipster.uaa.service.dto.UserDTO; import com.baeldung.jhipster.uaa.web.rest.errors.ExceptionTranslator; import com.baeldung.jhipster.uaa.web.rest.vm.KeyAndPasswordVM; import com.baeldung.jhipster.uaa.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the AccountResource REST controller. * * @see AccountResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) public class AccountResourceIntTest { @Autowired private UserRepository userRepository; @Autowired private AuthorityRepository authorityRepository; @Autowired private UserService userService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private HttpMessageConverter<?>[] httpMessageConverters; @Autowired private ExceptionTranslator exceptionTranslator; @Mock private UserService mockUserService; @Mock private MailService mockMailService; private MockMvc restMvc; private MockMvc restUserMockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(mockMailService).sendActivationEmail(any()); AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService); AccountResource accountUserMockResource = new AccountResource(userRepository, mockUserService, mockMailService); this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) .setMessageConverters(httpMessageConverters) .setControllerAdvice(exceptionTranslator) .build(); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) .setControllerAdvice(exceptionTranslator) .build(); } @Test public void testNonAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("")); } @Test public void testAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .with(request -> { request.setRemoteUser("test"); return request; }) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("test")); } @Test public void testGetExistingAccount() throws Exception { Set<Authority> authorities = new HashSet<>(); Authority authority = new Authority(); authority.setName(AuthoritiesConstants.ADMIN); authorities.add(authority); User user = new User(); user.setLogin("test"); user.setFirstName("john"); user.setLastName("doe"); user.setEmail("john.doe@jhipster.com"); user.setImageUrl("http://placehold.it/50x50"); user.setLangKey("en"); user.setAuthorities(authorities); when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.login").value("test")) .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 public void testGetUnknownAccount() throws Exception { when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(status().isInternalServerError()); } @Test @Transactional public 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").isPresent()).isFalse(); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); } @Test @Transactional public 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)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidEmail() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("password"); invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("invalid");// <-- invalid invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("123");// password with only 3 digits invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterNullPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword(null);// invalid null password invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public 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 restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); // Second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); assertThat(testUser.isPresent()).isTrue(); testUser.get().setActivated(true); userRepository.save(testUser.get()); // Second (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public 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 restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser1.isPresent()).isTrue(); // 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 restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser2.isPresent()).isFalse(); Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); assertThat(testUser3.isPresent()).isTrue(); // 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 restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) .andExpect(status().isCreated()); Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); assertThat(testUser4.isPresent()).isTrue(); assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); testUser4.get().setActivated(true); userService.updateUser((new UserDTO(testUser4.get()))); // Register 4th (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public 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)); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); Optional<User> userDup = userRepository.findOneByLogin("badguy"); assertThat(userDup.isPresent()).isTrue(); assertThat(userDup.get().getAuthorities()).hasSize(1) .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); } @Test @Transactional public 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.random(60)); user.setActivated(false); user.setActivationKey(activationKey); userRepository.saveAndFlush(user); restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) .andExpect(status().isOk()); user = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(user.getActivated()).isTrue(); } @Test @Transactional public void testActivateAccountWithWrongKey() throws Exception { restMvc.perform(get("/api/activate?key=wrongActivationKey")) .andExpect(status().isInternalServerError()); } @Test @Transactional @WithMockUser("save-account") public void testSaveAccount() throws Exception { User user = new User(); user.setLogin("save-account"); user.setEmail("save-account@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); 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)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(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.getActivated()).isEqualTo(true); assertThat(updatedUser.getAuthorities()).isEmpty(); } @Test @Transactional @WithMockUser("save-invalid-email") public void testSaveInvalidEmail() throws Exception { User user = new User(); user.setLogin("save-invalid-email"); user.setEmail("save-invalid-email@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); 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)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); } @Test @Transactional @WithMockUser("save-existing-email") public void testSaveExistingEmail() throws Exception { User user = new User(); user.setLogin("save-existing-email"); user.setEmail("save-existing-email@example.com"); user.setPassword(RandomStringUtils.random(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.random(60)); anotherUser.setActivated(true); userRepository.saveAndFlush(anotherUser); UserDTO userDTO = new UserDTO(); 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)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(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") public 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.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); 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)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(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") public void testChangePasswordWrongExistingPassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(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); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(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") public void testChangePassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password"); user.setEmail("change-password@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(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") public void testChangePasswordTooSmall() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-small"); user.setEmail("change-password-too-small@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new")))) .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") public void testChangePasswordTooLong() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-long"); user.setEmail("change-password-too-long@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, RandomStringUtils.random(101))))) .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") public void testChangePasswordEmpty() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("change-password-empty"); user.setEmail("change-password-empty@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password").content(RandomStringUtils.random(0))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional public void testRequestPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("password-reset@example.com")) .andExpect(status().isOk()); } @Test @Transactional public void testRequestPasswordResetUpperCaseEmail() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("password-reset@EXAMPLE.COM")) .andExpect(status().isOk()); } @Test public void testRequestPasswordResetWrongEmail() throws Exception { restMvc.perform( post("/api/account/reset-password/init") .content("password-reset-wrong-email@example.com")) .andExpect(status().isBadRequest()); } @Test @Transactional public void testFinishPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(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"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); } @Test @Transactional public void testFinishPasswordResetTooSmall() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset-too-small"); user.setEmail("finish-password-reset-too-small@example.com");
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
true
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/LogsResourceIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/LogsResourceIntTest.java
package com.baeldung.jhipster.uaa.web.rest; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.config.SecurityBeanOverrideConfiguration; import com.baeldung.jhipster.uaa.web.rest.vm.LoggerVM; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.LoggerContext; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Test class for the LogsResource REST controller. * * @see LogsResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) public class LogsResourceIntTest { private MockMvc restLogsMockMvc; @Before public void setup() { LogsResource logsResource = new LogsResource(); this.restLogsMockMvc = MockMvcBuilders .standaloneSetup(logsResource) .build(); } @Test public void getAllLogs() throws Exception { restLogsMockMvc.perform(get("/management/logs")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test public void changeLogs() throws Exception { LoggerVM logger = new LoggerVM(); logger.setLevel("INFO"); logger.setName("some.test.logger"); restLogsMockMvc.perform(put("/management/logs") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(logger))) .andExpect(status().isNoContent()); } @Test public void testLogstashAppender() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); assertThat(context.getLogger("ROOT").getAppender("ASYNC_LOGSTASH")).isInstanceOf(AsyncAppender.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/util/PaginationUtilUnitTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/util/PaginationUtilUnitTest.java
package com.baeldung.jhipster.uaa.web.rest.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpHeaders; /** * Tests based on parsing algorithm in app/components/util/pagination-util.service.js * * @see PaginationUtil */ public class PaginationUtilUnitTest { @Test public void generatePaginationHttpHeadersTest() { String baseUrl = "/api/_search/example"; List<String> content = new ArrayList<>(); Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl); List<String> strHeaders = headers.get(HttpHeaders.LINK); assertNotNull(strHeaders); assertTrue(strHeaders.size() == 1); String headerData = strHeaders.get(0); assertTrue(headerData.split(",").length == 4); String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\"," + "</api/_search/example?page=5&size=50>; rel=\"prev\"," + "</api/_search/example?page=7&size=50>; rel=\"last\"," + "</api/_search/example?page=0&size=50>; rel=\"first\""; assertEquals(expectedData, headerData); List<String> xTotalCountHeaders = headers.get("X-Total-Count"); assertTrue(xTotalCountHeaders.size() == 1); assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/errors/ExceptionTranslatorTestController.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/errors/ExceptionTranslatorTestController.java
package com.baeldung.jhipster.uaa.web.rest.errors; 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.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; @RestController public class ExceptionTranslatorTestController { @GetMapping("/test/concurrency-failure") public void concurrencyFailure() { throw new ConcurrencyFailureException("test concurrency failure"); } @PostMapping("/test/method-argument") public void methodArgument(@Valid @RequestBody TestDTO testDTO) { } @GetMapping("/test/parameterized-error") public void parameterizedError() { throw new CustomParameterizedException("test parameterized error", "param0_value", "param1_value"); } @GetMapping("/test/parameterized-error2") public void parameterizedError2() { Map<String, Object> params = new HashMap<>(); params.put("foo", "foo_value"); params.put("bar", "bar_value"); throw new CustomParameterizedException("test parameterized error", params); } @GetMapping("/test/missing-servlet-request-part") public void missingServletRequestPartException(@RequestPart String part) { } @GetMapping("/test/missing-servlet-request-parameter") public void missingServletRequestParameterException(@RequestParam String param) { } @GetMapping("/test/access-denied") public void accessdenied() { throw new AccessDeniedException("test access denied!"); } @GetMapping("/test/unauthorized") public void unauthorized() { throw new BadCredentialsException("test authentication failed!"); } @GetMapping("/test/response-status") public void exceptionWithReponseStatus() { throw new TestResponseStatusException(); } @GetMapping("/test/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-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/errors/ExceptionTranslatorIntTest.java
jhipster-modules/jhipster-uaa/uaa/src/test/java/com/baeldung/jhipster/uaa/web/rest/errors/ExceptionTranslatorIntTest.java
package com.baeldung.jhipster.uaa.web.rest.errors; import com.baeldung.jhipster.uaa.UaaApp; import com.baeldung.jhipster.uaa.config.SecurityBeanOverrideConfiguration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; 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; /** * Test class for the ExceptionTranslator controller advice. * * @see ExceptionTranslator */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UaaApp.class) public class ExceptionTranslatorIntTest { @Autowired private ExceptionTranslatorTestController controller; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; private MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(controller) .setControllerAdvice(exceptionTranslator) .setMessageConverters(jacksonMessageConverter) .build(); } @Test public void testConcurrencyFailure() throws Exception { mockMvc.perform(get("/test/concurrency-failure")) .andExpect(status().isConflict()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); } @Test public void testMethodArgumentNotValid() throws Exception { mockMvc.perform(post("/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("testDTO")) .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); } @Test public void testParameterizedError() throws Exception { mockMvc.perform(get("/test/parameterized-error")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("test parameterized error")) .andExpect(jsonPath("$.params.param0").value("param0_value")) .andExpect(jsonPath("$.params.param1").value("param1_value")); } @Test public void testParameterizedError2() throws Exception { mockMvc.perform(get("/test/parameterized-error2")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("test parameterized error")) .andExpect(jsonPath("$.params.foo").value("foo_value")) .andExpect(jsonPath("$.params.bar").value("bar_value")); } @Test public void testMissingServletRequestPartException() throws Exception { mockMvc.perform(get("/test/missing-servlet-request-part")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")); } @Test public void testMissingServletRequestParameterException() throws Exception { mockMvc.perform(get("/test/missing-servlet-request-parameter")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")); } @Test public void testAccessDenied() throws Exception { mockMvc.perform(get("/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 public void testUnauthorized() throws Exception { mockMvc.perform(get("/test/unauthorized")) .andExpect(status().isUnauthorized()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.401")) .andExpect(jsonPath("$.path").value("/test/unauthorized")) .andExpect(jsonPath("$.detail").value("test authentication failed!")); } @Test public void testMethodNotSupported() throws Exception { mockMvc.perform(post("/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' not supported")); } @Test public void testExceptionWithResponseStatus() throws Exception { mockMvc.perform(get("/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 public void testInternalServerError() throws Exception { mockMvc.perform(get("/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-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/ApplicationWebXml.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/ApplicationWebXml.java
package com.baeldung.jhipster.uaa; import com.baeldung.jhipster.uaa.config.DefaultProfileUtil; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; /** * This is a helper Java class that provides an alternative to creating a 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(UaaApp.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/UaaApp.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/UaaApp.java
package com.baeldung.jhipster.uaa; import com.baeldung.jhipster.uaa.config.ApplicationProperties; import com.baeldung.jhipster.uaa.config.DefaultProfileUtil; import io.github.jhipster.config.JHipsterConstants; 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.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.core.env.Environment; import javax.annotation.PostConstruct; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; @SpringBootApplication @EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class}) @EnableDiscoveryClient public class UaaApp { private static final Logger log = LoggerFactory.getLogger(UaaApp.class); private final Environment env; public UaaApp(Environment env) { this.env = env; } /** * Initializes uaa. * <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(UaaApp.class); DefaultProfileUtil.addDefaultProfile(app); Environment env = app.run(args).getEnvironment(); logApplicationStartup(env); } private static void logApplicationStartup(Environment env) { String protocol = "http"; if (env.getProperty("server.ssl.key-store") != null) { protocol = "https"; } String serverPort = env.getProperty("server.port"); String contextPath = env.getProperty("server.servlet.context-path"); if (StringUtils.isBlank(contextPath)) { contextPath = "/"; } 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("\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\t{}://localhost:{}{}\n\t" + "External: \t{}://{}:{}{}\n\t" + "Profile(s): \t{}\n----------------------------------------------------------", env.getProperty("spring.application.name"), protocol, serverPort, contextPath, protocol, hostAddress, serverPort, contextPath, env.getActiveProfiles()); String configServerStatus = env.getProperty("configserver.status"); if (configServerStatus == null) { configServerStatus = "Not found or not setup for this application"; } log.info("\n----------------------------------------------------------\n\t" + "Config Server: \t{}\n----------------------------------------------------------", configServerStatus); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/UserService.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/UserService.java
package com.baeldung.jhipster.uaa.service; import com.baeldung.jhipster.uaa.config.Constants; import com.baeldung.jhipster.uaa.domain.Authority; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.repository.AuthorityRepository; import com.baeldung.jhipster.uaa.repository.UserRepository; import com.baeldung.jhipster.uaa.security.AuthoritiesConstants; import com.baeldung.jhipster.uaa.security.SecurityUtils; import com.baeldung.jhipster.uaa.service.dto.UserDTO; import com.baeldung.jhipster.uaa.service.util.RandomUtil; import com.baeldung.jhipster.uaa.web.rest.errors.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.CacheManager; 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 java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.stream.Collectors; /** * 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; private final CacheManager cacheManager; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository, CacheManager cacheManager) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.authorityRepository = authorityRepository; this.cacheManager = cacheManager; } 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); this.clearUserCaches(user); 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().minusSeconds(86400))) .map(user -> { user.setPassword(passwordEncoder.encode(newPassword)); user.setResetKey(null); user.setResetDate(null); this.clearUserCaches(user); return user; }); } public Optional<User> requestPasswordReset(String mail) { return userRepository.findOneByEmailIgnoreCase(mail) .filter(User::getActivated) .map(user -> { user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(Instant.now()); this.clearUserCaches(user); return user; }); } public User registerUser(UserDTO userDTO, String password) { userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> { boolean removed = removeNonActivatedUser(existingUser); if (!removed) { throw new LoginAlreadyUsedException(); } }); 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()); 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); this.clearUserCaches(newUser); log.debug("Created Information for User: {}", newUser); return newUser; } private boolean removeNonActivatedUser(User existingUser){ if(existingUser.getActivated()) { return false; } userRepository.delete(existingUser); userRepository.flush(); this.clearUserCaches(existingUser); return true; } public User createUser(UserDTO userDTO) { User user = new User(); user.setLogin(userDTO.getLogin().toLowerCase()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); 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); this.clearUserCaches(user); log.debug("Created Information for User: {}", user); return 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); user.setEmail(email.toLowerCase()); user.setLangKey(langKey); user.setImageUrl(imageUrl); this.clearUserCaches(user); log.debug("Changed Information for User: {}", user); }); } /** * Update all information for a specific user, and return the modified user. * * @param userDTO user to update * @return updated user */ public Optional<UserDTO> updateUser(UserDTO userDTO) { return Optional.of(userRepository .findById(userDTO.getId())) .filter(Optional::isPresent) .map(Optional::get) .map(user -> { this.clearUserCaches(user); user.setLogin(userDTO.getLogin().toLowerCase()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); 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); this.clearUserCaches(user); log.debug("Changed Information for User: {}", user); return user; }) .map(UserDTO::new); } public void deleteUser(String login) { userRepository.findOneByLogin(login).ifPresent(user -> { userRepository.delete(user); this.clearUserCaches(user); log.debug("Deleted User: {}", user); }); } 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); this.clearUserCaches(user); log.debug("Changed password for User: {}", user); }); } @Transactional(readOnly = true) public Page<UserDTO> getAllManagedUsers(Pageable pageable) { return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new); } @Transactional(readOnly = true) public Optional<User> getUserWithAuthoritiesByLogin(String login) { return userRepository.findOneWithAuthoritiesByLogin(login); } @Transactional(readOnly = true) public Optional<User> getUserWithAuthorities(Long id) { return userRepository.findOneWithAuthoritiesById(id); } @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 .findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) .forEach(user -> { log.debug("Deleting not activated user {}", user.getLogin()); userRepository.delete(user); this.clearUserCaches(user); }); } /** * @return a list of all the authorities */ public List<String> getAuthorities() { return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList()); } private void clearUserCaches(User user) { Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE)).evict(user.getLogin()); Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE)).evict(user.getEmail()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/AuditEventService.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/AuditEventService.java
package com.baeldung.jhipster.uaa.service; import com.baeldung.jhipster.uaa.config.audit.AuditEventConverter; import com.baeldung.jhipster.uaa.repository.PersistenceAuditEventRepository; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.Optional; /** * Service for managing audit events. * <p> * This is the default implementation to support SpringBoot Actuator AuditEventRepository */ @Service @Transactional public class AuditEventService { private final PersistenceAuditEventRepository persistenceAuditEventRepository; private final AuditEventConverter auditEventConverter; public AuditEventService( PersistenceAuditEventRepository persistenceAuditEventRepository, AuditEventConverter auditEventConverter) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; } public Page<AuditEvent> findAll(Pageable pageable) { return persistenceAuditEventRepository.findAll(pageable) .map(auditEventConverter::convertToAuditEvent); } public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) { return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable) .map(auditEventConverter::convertToAuditEvent); } public Optional<AuditEvent> find(Long id) { return Optional.ofNullable(persistenceAuditEventRepository.findById(id)) .filter(Optional::isPresent) .map(Optional::get) .map(auditEventConverter::convertToAuditEvent); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/package-info.java
/** * Service layer beans. */ package com.baeldung.jhipster.uaa.service;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/MailService.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/MailService.java
package com.baeldung.jhipster.uaa.service; import com.baeldung.jhipster.uaa.domain.User; import io.github.jhipster.config.JHipsterProperties; import java.nio.charset.StandardCharsets; import java.util.Locale; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; 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.spring5.SpringTemplateEngine; /** * Service for sending emails. * <p> * We use the @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) { 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 (Exception e) { if (log.isDebugEnabled()) { log.warn("Email could not be sent to user '{}'", to, e); } else { log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); } } } @Async public void sendEmailFromTemplate(User user, String templateName, String titleKey) { 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); sendEmail(user.getEmail(), subject, content, false, true); } @Async public void sendActivationEmail(User user) { log.debug("Sending activation email to '{}'", user.getEmail()); sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title"); } @Async public void sendCreationEmail(User user) { log.debug("Sending creation email to '{}'", user.getEmail()); sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title"); } @Async public void sendPasswordResetMail(User user) { log.debug("Sending password reset email to '{}'", user.getEmail()); sendEmailFromTemplate(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-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/dto/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/dto/package-info.java
/** * Data Transfer Objects. */ package com.baeldung.jhipster.uaa.service.dto;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/dto/PasswordChangeDTO.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/dto/PasswordChangeDTO.java
package com.baeldung.jhipster.uaa.service.dto; /** * A DTO representing a password change required data - current and new password. */ public class PasswordChangeDTO { 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-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/dto/UserDTO.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/dto/UserDTO.java
package com.baeldung.jhipster.uaa.service.dto; import com.baeldung.jhipster.uaa.config.Constants; import com.baeldung.jhipster.uaa.domain.Authority; import com.baeldung.jhipster.uaa.domain.User; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.*; import java.time.Instant; import java.util.Set; import java.util.stream.Collectors; /** * A DTO representing a user, with his authorities. */ public class UserDTO { 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 = 6) private String langKey; private String createdBy; private Instant createdDate; private String lastModifiedBy; private Instant lastModifiedDate; private Set<String> authorities; public UserDTO() { // Empty constructor needed for Jackson. } public UserDTO(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.getActivated(); 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; } @Override public String toString() { return "UserDTO{" + "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-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/util/RandomUtil.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/util/RandomUtil.java
package com.baeldung.jhipster.uaa.service.util; import org.apache.commons.lang3.RandomStringUtils; /** * Utility class for generating random Strings. */ public final class RandomUtil { private static final int DEF_COUNT = 20; private RandomUtil() { } /** * Generate a password. * * @return the generated password */ public static String generatePassword() { return RandomStringUtils.randomAlphanumeric(DEF_COUNT); } /** * Generate an activation key. * * @return the generated activation key */ public static String generateActivationKey() { return RandomStringUtils.randomNumeric(DEF_COUNT); } /** * Generate a reset key. * * @return the generated reset key */ public static String generateResetKey() { return RandomStringUtils.randomNumeric(DEF_COUNT); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/mapper/package-info.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/mapper/package-info.java
/** * MapStruct mappers for mapping domain objects and Data Transfer Objects. */ package com.baeldung.jhipster.uaa.service.mapper;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/mapper/UserMapper.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/mapper/UserMapper.java
package com.baeldung.jhipster.uaa.service.mapper; import com.baeldung.jhipster.uaa.domain.Authority; import com.baeldung.jhipster.uaa.domain.User; import com.baeldung.jhipster.uaa.service.dto.UserDTO; import org.springframework.stereotype.Service; import java.util.*; import java.util.stream.Collectors; /** * Mapper for the entity User and its DTO called 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 UserDTO userToUserDTO(User user) { return new UserDTO(user); } public List<UserDTO> usersToUserDTOs(List<User> users) { return users.stream() .filter(Objects::nonNull) .map(this::userToUserDTO) .collect(Collectors.toList()); } public User userDTOToUser(UserDTO 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()); if (authorities != null) { user.setAuthorities(authorities); } return user; } } public List<User> userDTOsToUsers(List<UserDTO> userDTOs) { return userDTOs.stream() .filter(Objects::nonNull) .map(this::userDTOToUser) .collect(Collectors.toList()); } public User userFromId(Long id) { if (id == null) { return null; } User user = new User(); user.setId(id); return user; } public Set<Authority> authoritiesFromStrings(Set<String> strings) { return strings.stream().map(string -> { Authority auth = new Authority(); auth.setName(string); return auth; }).collect(Collectors.toSet()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/aop/logging/LoggingAspect.java
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/aop/logging/LoggingAspect.java
package com.baeldung.jhipster.uaa.aop.logging; import io.github.jhipster.config.JHipsterConstants; 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 java.util.Arrays; /** * 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 Logger log = LoggerFactory.getLogger(this.getClass()); 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.jhipster.uaa.repository..*)"+ " || within(com.baeldung.jhipster.uaa.service..*)"+ " || within(com.baeldung.jhipster.uaa.web.rest..*)") public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * 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(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); } } /** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice * @return result * @throws Throwable throws IllegalArgumentException */ @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false