Giter VIP home page Giter VIP logo

rieckpil / blog-tutorials Goto Github PK

View Code? Open in Web Editor NEW
752.0 752.0 758.0 27.86 MB

:star: Codebase for various tutorials about Java, Spring Boot, AWS, Kotlin, and Testing

Home Page: https://rieckpil.de/

License: MIT License

Java 82.74% JavaScript 2.99% HTML 6.61% Dockerfile 0.93% Shell 1.22% CSS 0.18% Batchfile 0.65% PLpgSQL 0.13% Groovy 0.07% Kotlin 2.32% TypeScript 2.05% Python 0.11%
aws java java-ee jdk junit kotlin maven microprofile postgresql react spring-boot spring-framework spring-security spring-test spring-web spring-webclient spring-webflux testcontainers

blog-tutorials's Introduction

Hi there 👋

I'm a hands-on IT consultant from 🇩🇪

With my blogging and YouTube efforts, I try to make testing Spring Boot applications more joyful (or at least less painful). By providing clear and concise guides with thorough explanations and best practices, I help developers incorporate testing into their daily routine rather than making it an afterthought 🧪

Say hi on Twitter 🐥 or LinkedIn 👔

Getting Started with Testing Spring Boot Java Applications

Testing Spring Boot Applications Demystified Unravel the complexities of testing Spring Boot applications. Gain insights, best practices, and practical tips and avoid common pitfalls to write comprehensive and effective tests to become more productive. Demystify Spring Boot testing and deliver robust & maintainable applications. » Get it here

Further Projects

Testing Spring Boot Applications Demystified

blog-tutorials's People

Contributors

aguibert avatar dependabot[bot] avatar nkengasongatem avatar rieckpil avatar torrespro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blog-tutorials's Issues

Can not get client used for request

Hi

I have implemented a ClientResponseFilter interface to handle a 302(redirection) response and registered it in to RestClientBuilder. I can't get the client, it returns always null.

public class FollowRedirectInterceptor implements ClientResponseFilter

{
@OverRide
public void filter(ClientRequestContext clientRequestContext, ClientResponseContext clientResponseContext) throws IOException
{

    if (clientResponseContext.getStatusInfo().getFamily().equals(Response.Status.Family.REDIRECTION)) 
	{
        Client client = clientRequestContext.getClient();
        WebTarget target = client.target(clientResponseContext.getLocation());
        Response response = target.request(clientRequestContext.getMediaType()).method(clientRequestContext.getMethod());

        clientResponseContext.setEntityStream((InputStream) response.getEntity());
        clientResponseContext.setStatusInfo(response.getStatusInfo());
        clientResponseContext.setStatus(response.getStatus());
    }
}

}

Issue with JSON-B and JAXB

Extracted from a comment on blog post: https://rieckpil.de/whatis-json-binding-json-b/

Let me give an example:

I have created a JAXB object called PersonType:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = “person-type”, propOrder = {
“firstName”,
“lastName”,
“age”,
“sex”
})
public class PersonType implements Serializable {

@XmlElement(name = “first-name”, required = true)
private String firstName;

@XmlElement(name = “last-name”, required = true)
private String lastName;

private int age;

@XmlElement(required = true)
@XmlSchemaType(name = “string”)
private SexType sex;

// getter and setter
}

I created a PersonType object and serialized it to JSON:

PersonType personType = new PersonType();
personType.setFirstName(“Lulseged”);
personType.setLastName(“Zerfu”);
personType.setAge(90);
personType.setSex(SexType.MALE);

Jsonb jsonb = JsonbBuilder.create();
System.out.println(jsonb.toJson(personType));

The result is:
{
“age”: 90,
“firstName”: “Lulseged”,
“lastName”: “Zerfu”,
“setAge”: true,
“setFirstName”: true,
“setLastName”: true,
“setSex”: true,
“sex”: “MALE”
}

What I expected to see was:

{
“age”: 90,
“firstName”: “Lulseged”,
“lastName”: “Zerfu”,
“sex”: “MALE”
}

I have to get ride of the sets:

“setAge”: true,
“setFirstName”: true,
“setLastName”: true,
“setSex”: true,

It works if the PersonType class was a plain old JAVA object.

By the way, I wonder why there is no JAXB in MicroProfile or even Jakarta has not updated it.

Thank you for your help.

inconsistent login behavior with jsf-simple-login-with-java-ee-security-api

For some reason it seems the authentication status that is returned sometimes is SEND_CONTINUE and other times is SUCCESS. When SUCCESS is returned then the result is the welcome page... but when the status is SEND_CONTINUE then nothing happens and the result is the login page with no error message.

running-java-within-postgres comment

Hi!

Thanks for the blog post about PL/Java. I noticed a couple of things that might allow it to be simplified.

  1. While your post says PL/Java is not available as a prebuilt package, as you are using debian in your example, in fact it is. If you enable the PostgreSQL debian repository, you can simply apt-get install postgresql-server-9.6 postgresql-9.6-pljava (along with whatever other packages you need at run time). There is then no need for maven, gcc, git, or any build-from-source process.
  2. The debian package of PL/Java declares its own dependency on default-java, so that package will be pulled in if you don't have it, without needing to be requested.
  3. When using the debian package, there is no need for SET pljava.libjvm_location as the packager has compiled in a default value that refers to the normal default-java package. Therefore, the pljava.libjvm_location variable only needs to be set if you wish to run PL/Java with a different Java runtime than the default.
  4. If the user postgres is a superuser in your database, there is no real need for GRANT USAGE ON LANGUAGE java TO postgres;.
  5. It might be worth mentioning that the jdbc:default:connection is not a conventional JDBC connection (it does not use PG's network protocol to converse with the backend); it is simply a shim that presents direct internal access to the backend via the familiar JDBC API.
  6. Code written for Java 7 or later would conventionally use try-with-resources when opening JDBC Connections, Statements, or ResultSets. (In PL/Java, for Connection it doesn't really matter, as that shim "connection" never closes anyway. But it is harmless, and for Statement or ResultSet it can ensure resources are released.)
  7. If a @Function annotation does not have a comment attribute, but the function has a javadoc comment, the first sentence of the javadoc will be used as the SQL function comment.

But those are minor points. I think the post did quite a good job covering the basics.

A couple more direct links into the documentation that might be helpful are to the Hello, world example (which is much like your own example but has a "further reading" list at the bottom) and, for production environments, the VM option recommendations page: Java's default VM options on a server machine kind of assume it has the machine to itself, and some tweaks to those options can greatly reduce its footprint when running in PostgreSQL.

Thanks for the coverage!

Question: Customize an auto-generated WebClient

Follow-up from Val on https://rieckpil.de/customize-spring-webclient-with-webclientcustomizer/

So, I have this code automatically generated by open-api:

ApiClient.java

…
public ApiClient() {
…
  WebClient.Builder webClient = WebClient.builder().exchangeStrategies(strategies);
  this.webClient = return webClient.build();
}

I cannot edit this code.

In a service, I’d like to call

ApiClient client = new ApiClient();

and get automatically a list of filters attached. Let’s say I want the same filters you show in this page, logResponse and logRequest. Because filters can only be attached to the builder and not after WebClient creation, and because the WebClient creation is part of a generated code that I cannot edit. I was stuck. Do you say that I can get what I want by

  1. Adding the WebClientCustomizer
@Component
public class ResponseLoggingCustomizer implements WebClientCustomizer {


  @Override
  public void customize(WebClient.Builder webClientBuilder) {
    webClientBuilder.filter(logResponse());
    webClientBuilder.filter(logRequest());
   }

  1. Creating this bean
@Bean
@Scope(“prototype”)
@ConditionalOnMissingBean
public Builder webClientBuilder(ObjectProvider customizerProvider) {
  Builder builder = WebClient.builder();
  customizerProvider.orderedStream().forEach((customizer) -> {
    customizer.customize(builder);
  });
  return builder;
}

I guess I miss something, right?

Mockito.mockStatic not working with Kotlin but it works in Java

Blog post you are referring to

https://rieckpil.de/mocking-static-methods-with-mockito-java-kotlin/

I was trying a mock a static method inside my Kotlin class for a unit test, but it seems the Java version of my Unit Test is successful but the Kotlin version is failing

@RunWith(RobolectricTestRunner.class)

public class MyTest {

    @Test
    public void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
        RestAdapterFactory restAdapterFactoryMock = Mockito.mock(RestAdapterFactory.class);
        try (MockedStatic<RestAdapterFactory> utilities = Mockito.mockStatic(RestAdapterFactory.class)) {
            utilities.when(() -> RestAdapterFactory.getInstance(Mockito.any()))
                    .thenReturn(restAdapterFactoryMock);

            assertEquals(restAdapterFactoryMock, RestAdapterFactory.getInstance("fd"));
        }
    }
}

This test is running successfully but the Kotlin version of it below is failing

Kotlin Version

@Test
fun givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
val restAdapterFactoryMock = Mockito.mock(RestAdapterFactory::class.java)
Mockito.mockStatic(RestAdapterFactory::class.java).use { utilities ->
utilities.`when`<Any> { getInstance(Mockito.any()) }.thenReturn(restAdapterFactoryMock)
Assert.assertEquals(restAdapterFactoryMock, getInstance("test"))
  }
} 

Getting the below exception:

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
    verify(mock).someMethod(contains("foo"))

Can someone help with this ?

Issue with variable replacement for Docx4j

Hey Rieckpil,
This is my code I don’t know what I want to replace the variable with the collection

public class DocxGenerator {

    private static final String TEMPLATE_NAME = “template.dotx”;

    public byte[] generateDocxFileFromTemplate() throws Exception {

        InputStream templateInputStream = this.getClass().getClassLoader().getResourceAsStream(TEMPLATE_NAME);

        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);

        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

        List colorlist = new ArrayList();
        colorlist.add(“red”);
        colorlist.add(“white”);
        colorlist.add(“green”);

        VariablePrepare.prepare(wordMLPackage);

        java.util.HashMap variables = new java.util.HashMap();
        VariablePrepare.prepare(wordMLPackage);
        variables.put(“firstName”, “sathish”);
        variables.put(“lastName”, “kumar”);
        variables.put(“colorlist”, colorlist);

        documentPart.variableReplace(variables);

    }
}

My document template:

My name is ${firstName} ${lastName}
My favourite colors are ${colorlist}

> I assume you can't replace the `${colorlist}` variable with a Java collection type as the `.variableReplace()` method of docx4j has the following signature `public void variableReplace(java.util.Map<String, String> mappings) throws JAXBException, Docx4JException` and is therefor expecting a `Map<String, String>`.

I assume you can't replace the ${colorlist} variable with a Java collection type as the .variableReplace() method of docx4j has the following signature public void variableReplace(java.util.Map<String, String> mappings) throws JAXBException, Docx4JException and is therefor expecting a Map<String, String>.

If you just want to render the content of your List, you can do the following:

 variables.put("colorlist", Arrays.asList("blue", "red", "white").stream().collect(Collectors.joining(", ")));

and the output on the document should be: blue, red, white.

Otherwise please have a look at the library itself or ask the question again on StackOverflow.

Hi rieckpil,
I want to iterate it by one by one like this
1.blue
2.red
3.white
what I want to do change in my template so far I used the foreach in the template but it doesnt works

Originally posted by @sathish38 in #9 (comment)

Unable to login after successful sign up

WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Failed jdbc login for Emmanuel.|#]

Thats the error I find whenever I try to login after successful sign up
The following is my full code
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    /
    package com.loginView;
    /
    *
  • @author Emmanuel Msafiri Phiri
    */
    import com.cims2019EJB.UserEJB;
    import com.cims2019Entity.User;
    import javax.annotation.ManagedBean;
    import javax.enterprise.context.SessionScoped;
    import javax.inject.Named;
    import java.io.Serializable;
    import java.security.Principal;
    import java.util.Map;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.faces.application.FacesMessage;
    //import javax.faces.bean.ManagedBean;
    //import javax.faces.bean.SessionScoped;
    import javax.faces.context.ExternalContext;
    import javax.faces.context.FacesContext;
    import javax.inject.Inject;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;

@nAmed("loginView")
@ManagedBean
@SessionScoped
public class LoginView implements Serializable {

private static final long serialVersionUID = 3254181235309041386L;
private static Logger log = Logger.getLogger(LoginView.class.getName());
@Inject
private UserEJB userEJB;
private String username;
private String password;
private User user;

public String login() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    try {
        request.login(username, password
        );
    } catch (ServletException e) {
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login Failed!", null));
        return "login.xhtml";
    }
    Principal principal = request.getUserPrincipal();
    this.user = userEJB.findUserById(principal.getName());
    log.log(Level.INFO, "Authentication done for user: {0}", principal.getName());
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    Map<String, Object> sessionMap = externalContext.getSessionMap();
    sessionMap.put("User", user);   
    if (request.isUserInRole("users")) {     
        return "/user/sc.xhtml?faces-redirect=true";
    } else if (request.isUserInRole("admin")) {
            return "/admin/admin.xhtml?faces-redirect=true";
        }    
     else if (request.isUserInRole("SC_user")) {
            return "/SC_user/privatepage?faces-redirect=true";
        }
     else if (request.isUserInRole("Cardseb_user")) {
            return "/Cardseb_user/privatepage?faces-redirect=true";
        }
     else{
         return "login.xhtml";
    }
}
public String logout() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    try {
        this.user = null;
        request.logout();
        // clear the session
        ((HttpSession) context.getExternalContext().getSession(false)).invalidate();
    } catch (ServletException e) {
        log.log(Level.SEVERE, "Failed to logout user!", e);
    }
    return "/login.xhtml?faces-redirect=true";
}

public User getAuthenticatedUser() {
    return user;
}

public static Logger getLog() {
    return log;
}

public static void setLog(Logger log) {
    LoginView.log = log;
}

public UserEJB getUserEJB() {
    return userEJB;
}

public void setUserEJB(UserEJB userEJB) {
    this.userEJB = userEJB;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}
public User getUser() {
    return user;
}
public void setUser(User user) {
    this.user = user;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}

}

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.cims201SecurityEntity;

import com.cims2019EJB.UserEJB;
import com.cims2019Entity.User;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.ManagedBean;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Inject;
import javax.inject.Named;

/**
*

  • @author LOGIMATE USER
    */
    @nAmed(value="registerView")
    @ManagedBean
    @SessionScoped
    public class RegisterView implements Serializable {
    private static final long serialVersionUID = 1685823449195612778L;
    private static Logger log = Logger.getLogger(RegisterView.class.getName());
    @Inject
    private UserEJB userEJB;
    private String username;
    private String email;
    private String password;
    private String confirmPassword;
    public void validatePassword(ComponentSystemEvent event) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    UIComponent components = event.getComponent();
    //get password
    UIInput uiInputPassword = (UIInput) components.findComponent("password");
    String password = uiInputPassword.getLocalValue() == null ? "" : uiInputPassword.getLocalValue().toString();
    String passwordId = uiInputPassword.getClientId();
    // get confirm password
    UIInput uiInputConfirmPassword = (UIInput) components.findComponent("confirmpassword");
    String confirmPassword = uiInputConfirmPassword.getLocalValue() == null ? ""
    : uiInputConfirmPassword.getLocalValue().toString();
    // Let required="true" do its job.
    if (password.isEmpty() || confirmPassword.isEmpty()) {
    return;
    }
    if (!password.equals(confirmPassword)) {
    FacesMessage msg = new FacesMessage("Confirm password does not match password");
    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
    facesContext.addMessage(passwordId, msg);
    facesContext.renderResponse();
    }
    if (userEJB.findUserById(email) != null) {
    FacesMessage msg = new FacesMessage("User with this e-mail already exists");
    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
    facesContext.addMessage(passwordId, msg);
    facesContext.renderResponse();
    }
    }
    public String register() {
    User user = new User(email, password, username);
    //System.out.println("The Registered Users");
    userEJB.createUser(user);
    log.log(Level.INFO, "New user created with e-mail: {0} and name: {1}", new Object[]{email, username});

             return "regdone.xhtml";
    

    }

    public static Logger getLog() {
    return log;
    }

    public static void setLog(Logger log) {
    RegisterView.log = log;
    }

    public UserEJB getUserEJB() {
    return userEJB;
    }

    public void setUserEJB(UserEJB userEJB) {
    this.userEJB = userEJB;
    }

    public String getUsername() {
    return username;
    }

    public void setUsername(String username) {
    this.username = username;
    }

    public String getEmail() {
    return email;
    }
    public void setEmail(String email) {
    this.email = email;
    }
    public String getPassword() {
    return password;
    }
    public void setPassword(String password) {
    this.password = password;
    }
    public String getConfirmPassword() {
    return confirmPassword;
    }
    public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
    }
    }

<title>CIMS</title> <style> h4{ font-family: sans-serif; color: silver; text-align=left; } </style>
    <h:body>        
        <!--<pe:layout resizerTip="Resize Me" togglerTipClosed="Open Me" 
                   togglerTipOpen="Close Me" fullpage="false" style="">-->
        <p:layout style="min-width:390px;min-height:30px;background-color:#040d8a;">
            <h4>CIMS Online</h4>  
        </p:layout>
        <p:outputPanel>
            <div class="ui-g">
                <div class="ui-g-4"/>
                <div class="ui-g-4">
                    <h:form id="login">
                        <p:growl id="msg" showDetail="true" life="3000" />
                        <h3><img src="loginLogo.JPG" alt=""/></h3>
                        <p:panel header="CIMS-Login" style="width: 390px; background-image: url('clasic card.jpg'); background-color: #040d8a" >

                            <p:messages id="messages" globalOnly="true"/>
                            <h:panelGrid columns="3" cellpadding="5" style="margin: 0 auto;">
                                <h:outputLabel style='color:white' for="username" value="E-Mail"/>
                                <h:inputText id="username" value="#{loginView.username}" required="true" requiredMessage="Please enter your e-mail address"/>
                                <p:message for="username"/>
                                <p:outputLabel style='color:white' for="password" value="Password"/>
                                <h:inputSecret id="password" value="#{loginView.password}" required="true" requiredMessage="Please enter password"/>
                                <p:message for="password"/>
                                <p:commandButton id="submit" update="@form" 
                                                 value="Login" style="color: black" action="#{loginView.login}"/>
                            <h:link value="Register" outcome="/Register.xhtml" />
                            </h:panelGrid>
                        </p:panel>
                    </h:form>
                </div>
            </div>
        </p:outputPanel>
    </h:body>
</f:view>
<title>Register</title>

Create new account

Name: E-Mail: Password: Confirm password:

</h:body>

jsf 2.3 User Signup not working

Hello I need Help I have the definitive guide to jsf 2.3 but I can not find more details about user sign up process and its bean. your imediate help will be highly appriciated.

Test a Spring MVC Thymeleaf View @Controller POST Endpoint

Blog post you are referring to

https://gitlab.com/mimLau/nurselink-web-client/-/blob/develop/src/test/java/com/lau/nurselink/webclient/webapp/controllers/AppHistoryStatusControllerTest.java

https://gitlab.com/mimLau/nurselink-web-client/-/blob/develop/src/main/java/com/lau/nurselink/webclient/webapp/controllers/AppHistoryStatusController.java

Your Question

Hi, here is my question :
In the first link you will find AppHistoryStatusControllerTest class where I want to test a Post mapping endpoint. I mocked appHistoryStatusServiceMock, and return an appHistoryStatus, but at controller side (AppHistoryStatusController class), appHistoryStatus was null. I tried to put appHistoryStatus in a jsonRequest, but still null. I added at controller side @requestbody before the argument, the test successed but when I launched my application, the mapping was not working anymore, and I had this message error "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported".

Thank you !!

Context (Environment, Dependency Versions, Framework)

Java 11, spring boot, Windows 11, Thymeleaf

Getting 401 unauthorised error while deploying kubernetes on local machine

Deploy your Spring Boot Application to a local Kubernetes Cluster

After Executing kubectl apply -f deployment.yml to deploy the application to Kubernetes. Up to this step its works fine.

Expected Behavior

i am not able to get result . when i am hitting with this URL "http://localhost:31000/api/messages"

i am getting below error :

  • Connection #0 to host 127.0.0.1 left intact
    {"timestamp":"2020-06-17T14:52:34.163+00:00","status":401,"error":"Unauthorized","message":"","path":"/api/messages"}* C

Context (Environment)

. MAC

test insert with mongodb by making get request

Blog post you are referring to

blog from url: https://rieckpil.de/mongodb-testcontainers-setup-for-datamongotest/

Your Question

im trying to make simple insert database testing, below is my test code

@Testcontainers
@SpringBootTest
@DisplayName("users testing")
@DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
class OrderApplicationUsersTests {
	
	@Container
	static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:6.0.3"));

	@DynamicPropertySource
	static void setProperties(DynamicPropertyRegistry registry) {
		registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
	}
	
	private UserRepository userRepo;
	
	private String uriContainer = mongoDBContainer.getIpAddress();
	
	@Test
	@DisplayName("add admin")
	void isertAdmin() throws IOException {
		userRepo.deleteAll();
		URL url = new URL(uriContainer + "/users/admin");
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();
		String encoding = conn.getContentEncoding();
		encoding = encoding == null ? "UTF-8" : encoding;
		String body = IOUtils.toString(in, encoding);
		MatcherAssert.assertThat(body, CoreMatchers.containsString("admin generated"));
	}
	
	@Test
	@DisplayName("add admin failed")
	void isertAdminTwice() throws IOException {
		URL url = new URL(uriContainer + "/users/admin");
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();
		String encoding = conn.getContentEncoding();
		encoding = encoding == null ? "UTF-8" : encoding;
		String body = IOUtils.toString(in, encoding);
		MatcherAssert.assertThat(body, CoreMatchers.containsString("admin only generated once"));
	}

also already post question to stackoverflow https://stackoverflow.com/questions/75198138/how-to-keep-data-when-testing-insert-to-mongodb-collection-with-spring-inside-do

Context (Environment, Dependency Versions, Framework)

dna@dna:~$ java --version
openjdk 17.0.5 2022-10-18
OpenJDK Runtime Environment (build 17.0.5+8-Ubuntu-2ubuntu122.04)
OpenJDK 64-Bit Server VM (build 17.0.5+8-Ubuntu-2ubuntu122.04, mixed mode, sharing)
dna@dna:~$ mvn --version
Apache Maven 3.6.3
Maven home: /usr/share/maven
Java version: 17.0.5, vendor: Private Build, runtime: /usr/lib/jvm/java-17-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "5.15.0-41-generic", arch: "amd64", family: "unix"

my pom.xml https://github.com/dhanyn10/tes-jejakin-be/blob/main/order/pom.xml
im using Linux Mint 21 Cinnamon
my error log: https://github.com/dhanyn10/tes-jejakin-be/actions/runs/3980299926/jobs/6823284040

Error Login

Hi Philip, I tried to import the project in eclipse and I compiled with maven and I ran with wildfly 18.0.1 but when I log in with any user I get this exception but I don't understand what it is due to:

`15:17:26,224 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-3) #{loginBacking.submit}: java.lang.NoClassDefFoundError: de/rieckpil/blog/LoginBacking$1: javax.faces.FacesException: #{loginBacking.submit}: java.lang.NoClassDefFoundError: de/rieckpil/blog/LoginBacking$1
at [email protected]//com.sun.faces.application.ActionListenerImpl.getNavigationOutcome(ActionListenerImpl.java:96)
at [email protected]//com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:71)
at [email protected]//javax.faces.component.UICommand.broadcast(UICommand.java:222)
at [email protected]//javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:847)
at [email protected]//javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1395)
at [email protected]//com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:58)
at [email protected]//com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
at [email protected]//com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
at [email protected]//javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:707)
at [email protected]//javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
at [email protected]//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
at [email protected]//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at [email protected]//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at [email protected]//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at [email protected]//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at [email protected]//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at [email protected]//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
at [email protected]//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at [email protected]//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:53)
at [email protected]//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at [email protected]//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at [email protected]//io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:59)
at [email protected]//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at [email protected]//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at [email protected]//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at [email protected]//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//org.wildfly.extension.undertow.security.jaspi.JASPICSecureResponseHandler.handleRequest(JASPICSecureResponseHandler.java:48)
at [email protected]//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
at [email protected]//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at [email protected]//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at [email protected]//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
at [email protected]//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
at [email protected]//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at [email protected]//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at [email protected]//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: javax.faces.el.EvaluationException: java.lang.NoClassDefFoundError: de/rieckpil/blog/LoginBacking$1
at [email protected]//com.sun.faces.application.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:76)
at [email protected]//com.sun.faces.application.ActionListenerImpl.getNavigationOutcome(ActionListenerImpl.java:82)
... 59 more
Caused by: java.lang.NoClassDefFoundError: de/rieckpil/blog/LoginBacking$1
at deployment.jsf-simple-login.war//de.rieckpil.blog.LoginBacking.submit(LoginBacking.java:43)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at [email protected]//com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:157)
at [email protected]//com.sun.el.parser.AstValue.invoke(AstValue.java:265)
at [email protected]//com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:280)
at [email protected]//org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at [email protected]//org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at [email protected]//org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at [email protected]//org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at [email protected]//com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:65)
at [email protected]//com.sun.faces.application.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:66)
... 60 more
Caused by: java.lang.ClassNotFoundException: de.rieckpil.blog.LoginBacking$1 from [Module "deployment.jsf-simple-login.war" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:255)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
... 74 more

15:17:26,230 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-3) javax.faces.el.EvaluationException: java.lang.NoClassDefFoundError: de/rieckpil/blog/LoginBacking$1
at [email protected]//com.sun.faces.application.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:76)
at [email protected]//com.sun.faces.application.ActionListenerImpl.getNavigationOutcome(ActionListenerImpl.java:82)
at [email protected]//com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:71)
at [email protected]//javax.faces.component.UICommand.broadcast(UICommand.java:222)
at [email protected]//javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:847)
at [email protected]//javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1395)
at [email protected]//com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:58)
at [email protected]//com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
at [email protected]//com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
at [email protected]//javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:707)
at [email protected]//javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
at [email protected]//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
at [email protected]//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at [email protected]//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at [email protected]//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at [email protected]//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at [email protected]//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at [email protected]//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
at [email protected]//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at [email protected]//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:53)
at [email protected]//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at [email protected]//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at [email protected]//io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:59)
at [email protected]//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at [email protected]//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at [email protected]//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at [email protected]//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//org.wildfly.extension.undertow.security.jaspi.JASPICSecureResponseHandler.handleRequest(JASPICSecureResponseHandler.java:48)
at [email protected]//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
at [email protected]//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at [email protected]//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at [email protected]//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
at [email protected]//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
at [email protected]//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at [email protected]//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at [email protected]//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NoClassDefFoundError: de/rieckpil/blog/LoginBacking$1
at deployment.jsf-simple-login.war//de.rieckpil.blog.LoginBacking.submit(LoginBacking.java:43)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at [email protected]//com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:157)
at [email protected]//com.sun.el.parser.AstValue.invoke(AstValue.java:265)
at [email protected]//com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:280)
at [email protected]//org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at [email protected]//org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at [email protected]//org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at [email protected]//org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at [email protected]//com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:65)
at [email protected]//com.sun.faces.application.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:66)
... 60 more
Caused by: java.lang.ClassNotFoundException: de.rieckpil.blog.LoginBacking$1 from [Module "deployment.jsf-simple-login.war" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:255)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
... 74 more

`

Export file docx by template using docx4j output auto add "generated with Docx4j on Wildfly" to the footer

Blog post you are referring to

link blog: https://rieckpil.de/howto-generate-documents-from-word-templates-with-docx4j-on-wildfly-14/
link src code: https://github.com/rieckpil/blog-tutorials/tree/master/generate-documents-from-word-templates-with-docx4j-on-wildfly14

Expected Behavior

Show by template input.docx without add more in footer

Current Behavior

Show in footer of file output.docx "generated with Docx4j on Wildfly"

Steps to Reproduce

lib maven pom.xml

org.docx4j
docx4j-JAXB-Internal
8.0.0


org.docx4j
docx4j-JAXB-ReferenceImpl
8.0.0


org.docx4j
docx4j-JAXB-MOXy
8.0.0


org.docx4j
docx4j-export-fo
8.0.0

code java:
public static void generateDocxFileFromTemplate() throws Exception {
// TODO - ref: https://github.com/rieckpil/blog-tutorials/tree/master/generate-documents-from-word-templates-with-docx4j-on-wildfly14
InputStream templateInputStream = new FileInputStream("C:\Users\thangnm\Desktop\template (1).docx");

	WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);

	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

	VariablePrepare.prepare(wordMLPackage);

	HashMap<String, String> variables = new HashMap<>();
	variables.put("firstName", "userInformation.getFirstName()");
	variables.put("lastName", "userInformation.getLastName()");
    variables.put("salutation", "userInformation.getSalutation()");
	variables.put("message", "userInformation.getMessage()");

	documentPart.variableReplace(variables);

	String outputfilepath = "C:\\Users\\thangnm\\Desktop\\template (2).docx";
	FileOutputStream os = new FileOutputStream(outputfilepath);

	wordMLPackage.save(os);
	os.flush();
	os.close();
}

Please help me, thanks!!!

the lifecycle of GreenMail per method to execute two independent methods

Blog post you are referring to

Refers to: blog post "Use GreenMail For Spring Mail (JavaMailSender) JUnit 5 Integration Tests"
https://rieckpil.de/use-greenmail-for-spring-mail-javamailsender-junit-5-integration-tests/

Your Question

I test 2 methods inside test class, when I test them separately (withPerMethodLifecycle(false) -as in post) everything works fine, however if I test the whole class – the MimeMessage[] array in second method holds 2 messages (one from previous method I suppose), not one. Setting methodLifecycle to true makes loading application context impossible(“mail server is not available”, “failed to load ApplicationContext”). I did not understand what some code at blog post does, so I made some changes to undestand the code I'm using. Any ideas what might help? I’d be grateful!

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(MockitoExtension.class)
class EmailServiceTest {
    @RegisterExtension
    static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP)
            .withConfiguration(GreenMailConfiguration.aConfig().withUser("admin", "root"))
            .withPerMethodLifecycle(true);

    @Autowired
    EmailSender emailSender;
    final String RECIPIENT = "[email protected]";
    final String CONTENT = "test content";
    final String SENDER = "[email protected]";

    @Test
    void sendConfirmationEmail_should_send_confirmation_email() throws MessagingException, IOException {

        String subject = "Confirm your email";
        greenMail.start();

        emailSender.sendConfirmationEmail(RECIPIENT, CONTENT);
        MimeMessage[] receivedMessages = greenMail.getReceivedMessages();

        assertThat(receivedMessages.length).isEqualTo(1);

        await().atMost(2, SECONDS).untilAsserted(() -> {
            MimeMessage receivedMessage = receivedMessages[0];
            assertThat(receivedMessage.getAllRecipients()[0].toString()).isEqualTo(RECIPIENT);
            assertThat(receivedMessage.getFrom()[0].toString()).isEqualTo(SENDER);
            assertThat(receivedMessage.getSubject()).isEqualTo(subject);
            assertThat(receivedMessage.getContent().toString()).contains(CONTENT);
        });
    }

    @Test
    void sendNotificationEmail_should_send_notification_email() throws MessagingException, IOException {
        String subject = "Notification about recent changes to issue reported by you";
        emailSender.sendNotificationEmail(RECIPIENT, CONTENT);
        MimeMessage[] receivedMessages = greenMail.getReceivedMessages();
        await().atMost(2, SECONDS).untilAsserted(() -> {
            assertThat(receivedMessages.length).isEqualTo(1); 
            MimeMessage receivedMessage = receivedMessages[0];
            assertThat(receivedMessage.getAllRecipients()[0].toString()).isEqualTo(RECIPIENT);
            assertThat(receivedMessage.getFrom()[0].toString()).isEqualTo(SENDER);
            assertThat(receivedMessage.getSubject()).isEqualTo(subject);
            assertThat(receivedMessage.getContent().toString()).contains(CONTENT);
        });

    }
}

application-test.yml

spring:
    mail:
        password: root
        username: admin
        host: localhost
        port: 3025 # default protocol port + 3000 as offset-->
        protocol: smtp
        test-connection: true

Stacktrace:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Mail server is not available
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:315) ~[spring-beans-5.3.13.jar:5.3.13]
	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:296) ~[spring-beans-5.3.13.jar:5.3.13]
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Mail server is not available
	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224) ~[spring-beans-5.3.13.jar:5.3.13]
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) ~[spring-beans-5.3.13.jar:5.3.13]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:311) ~[spring-beans-5.3.13.jar:5.3.13]
	...
Caused by: java.lang.IllegalStateException: Mail server is not available
	at org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration.validateConnection(MailSenderValidatorAutoConfiguration.java:54) ~[spring-boot-autoconfigure-2.6.0.jar:2.6.0]
	at org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration.<init>(MailSenderValidatorAutoConfiguration.java:46) ~[spring-boot-autoconfigure-2.6.0.jar:2.6.0]
...
Caused by: java.net.ConnectException: Connection refused: connect
	at java.base/java.net.PlainSocketImpl.waitForConnect(Native Method) ~[na:na]
	at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:107) ~[na:na]
	at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
	at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
	at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
	...

2022-02-04 10:46:51.827 ERROR 15320 --- [    Test worker] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@3088660d] to prepare test instance [com.poludnikiewicz.bugtracker.email.EmailServiceTest@6c98079]

java.lang.IllegalStateException: Failed to load ApplicationContext
	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132) ~[spring-test-5.3.13.jar:5.3.13]
	at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124) ~[spring-test-5.3.13.jar:5.3.13]
	at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) ~[spring-test-5.3.13.jar:5.3.13]
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Mail server is not available
	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224) ~[spring-beans-5.3.13.jar:5.3.13]
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) ~[spring-beans-5.3.13.jar:5.3.13]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:311) ~[spring-beans-5.3.13.jar:5.3.13]
	... 
Caused by: java.lang.IllegalStateException: Mail server is not available
	at org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration.validateConnection(MailSenderValidatorAutoConfiguration.java:54) ~[spring-boot-autoconfigure-2.6.0.jar:2.6.0]
	at org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration.<init>(MailSenderValidatorAutoConfiguration.java:46) ~[spring-boot-autoconfigure-2.6.0.jar:2.6.0]
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:na]
...
Caused by: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 3025; timeout 5000
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2210) ~[jakarta.mail-1.6.7.jar:1.6.7]
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:722) ~[jakarta.mail-1.6.7.jar:1.6.7]
	at javax.mail.Service.connect(Service.java:342) ~[jakarta.mail-1.6.7.jar:1.6.7]
	at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:518) ~[spring-context-support-5.3.13.jar:5.3.13]
...
Caused by: java.net.ConnectException: Connection refused: connect
	at java.base/java.net.PlainSocketImpl.waitForConnect(Native Method) ~[na:na]
	at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:107) ~[na:na]
	at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
	at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
	at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
	at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na]
	at java.base/java.net.Socket.connect(Socket.java:609) ~[na:na]
	at com.sun.mail.util.WriteTimeoutSocket.connect(WriteTimeoutSocket.java:91) ~[jakarta.mail-1.6.7.jar:1.6.7]
	at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:333) ~[jakarta.mail-1.6.7.jar:1.6.7]
	at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:214) ~[jakarta.mail-1.6.7.jar:1.6.7]
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2160) ~[jakarta.mail-1.6.7.jar:1.6.7]
	...
Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
	at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
	at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Mail server is not available
	at app//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:315)
	at app//org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:296)
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Mail server is not available
	at app//org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224)
	at app//org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117)
	at app//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:311)
	... 
Caused by: java.lang.IllegalStateException: Mail server is not available
	at org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration.validateConnection(MailSenderValidatorAutoConfiguration.java:54)
	at org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration.<init>(MailSenderValidatorAutoConfiguration.java:46)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	...
Caused by: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 3025; timeout 5000;
  nested exception is:
	java.net.ConnectException: Connection refused: connect
	at app//com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2210)
	at app//com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:722)
	at app//javax.mail.Service.connect(Service.java:342)
	at app//org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:518)
	at app//org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:398)
	at app//org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration.validateConnection(MailSenderValidatorAutoConfiguration.java:51)
	... 
Caused by: java.net.ConnectException: Connection refused: connect
	at java.base/java.net.PlainSocketImpl.waitForConnect(Native Method)
	at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:107)
	at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
	at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
	at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
	at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
	at java.base/java.net.Socket.connect(Socket.java:609)
	at com.sun.mail.util.WriteTimeoutSocket.connect(WriteTimeoutSocket.java:91)
	at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:333)
	at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:214)
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2160)
	...


Context (Environment, Dependency Versions, Framework)

GreenMail, SpringBoot, JUnit5, Java 11

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.