001/*
002 * Copyright 2002-2012 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.jdbc.support.lob;
018
019import javax.transaction.Synchronization;
020
021import org.springframework.util.Assert;
022
023/**
024 * Callback for resource cleanup at the end of a JTA transaction.
025 * Invokes {@code LobCreator.close()} to clean up temporary LOBs
026 * that might have been created.
027 *
028 * @author Juergen Hoeller
029 * @since 2.0
030 * @see LobCreator#close()
031 * @see javax.transaction.Transaction#registerSynchronization
032 */
033public class JtaLobCreatorSynchronization implements Synchronization {
034
035        private final LobCreator lobCreator;
036
037        private boolean beforeCompletionCalled = false;
038
039
040        /**
041         * Create a JtaLobCreatorSynchronization for the given LobCreator.
042         * @param lobCreator the LobCreator to close after transaction completion
043         */
044        public JtaLobCreatorSynchronization(LobCreator lobCreator) {
045                Assert.notNull(lobCreator, "LobCreator must not be null");
046                this.lobCreator = lobCreator;
047        }
048
049        @Override
050        public void beforeCompletion() {
051                // Close the LobCreator early if possible, to avoid issues with strict JTA
052                // implementations that issue warnings when doing JDBC operations after
053                // transaction completion.
054                this.beforeCompletionCalled = true;
055                this.lobCreator.close();
056        }
057
058        @Override
059        public void afterCompletion(int status) {
060                if (!this.beforeCompletionCalled) {
061                        // beforeCompletion not called before (probably because of JTA rollback).
062                        // Close the LobCreator here.
063                        this.lobCreator.close();
064                }
065        }
066
067}