View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
17   */
18  
19  package org.mycore.restapi;
20  
21  import java.io.IOException;
22  
23  import org.apache.logging.log4j.LogManager;
24  import org.apache.logging.log4j.Logger;
25  import org.mycore.common.MCRSession;
26  import org.mycore.common.MCRSessionMgr;
27  import org.mycore.common.MCRTransactionHelper;
28  
29  import jakarta.annotation.Priority;
30  import jakarta.ws.rs.InternalServerErrorException;
31  import jakarta.ws.rs.Priorities;
32  import jakarta.ws.rs.container.ContainerRequestContext;
33  import jakarta.ws.rs.container.ContainerRequestFilter;
34  
35  @Priority(Priorities.USER)
36  public class MCRTransactionFilter implements ContainerRequestFilter {
37  
38      public static final String PROP_REQUIRE_TRANSACTION = "mcr:jpaTrans";
39  
40      public static final Logger LOGGER = LogManager.getLogger();
41  
42      @Override
43      public void filter(ContainerRequestContext requestContext) throws IOException {
44          if (MCRSessionMgr.isLocked()) {
45              return;
46          }
47          MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
48          if (MCRTransactionHelper.isTransactionActive()) {
49              LOGGER.debug("Filter scoped JPA transaction is active.");
50              if (MCRTransactionHelper.transactionRequiresRollback()) {
51                  try {
52                      MCRTransactionHelper.rollbackTransaction();
53                  } finally {
54                      throw new InternalServerErrorException("Transaction rollback was required.");
55                  }
56              }
57              MCRTransactionHelper.commitTransaction();
58          }
59          if (Boolean.TRUE.equals(requestContext.getProperty(PROP_REQUIRE_TRANSACTION))) {
60              LOGGER.debug("Starting user JPA transaction.");
61              MCRTransactionHelper.beginTransaction();
62          }
63      }
64  }