<commit_before>/*
 * #%L
 * BroadleafCommerce Common Libraries
 * %%
 * Copyright (C) 2009 - 2014 Broadleaf Commerce
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
package org.broadleafcommerce.common.util.tenant;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.site.domain.Catalog;
import org.broadleafcommerce.common.site.domain.Site;
import org.broadleafcommerce.common.util.TransactionUtils;
import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * The utility methods in this class provide a way to ignore the currently configured site/catalog contexts and instead
 * explicitly run operations in the specified context.
 * 
 * @author <NAME>
 */
public class IdentityExecutionUtils {

    private static final Log LOG = LogFactory.getLog(IdentityExecutionUtils.class);

    public static <T, G extends Throwable> T runOperationByIdentifier(IdentityOperation<T, G> operation, Site site, Catalog catalog,
                                                              PlatformTransactionManager transactionManager) throws G {
        IdentityUtilContext context = new IdentityUtilContext();
        context.setIdentifier(site);
        IdentityUtilContext.setUtilContext(context);

        boolean isNew = initRequestContext(site, catalog);

        activateSession();

        TransactionContainer container = establishTransaction(transactionManager);
        boolean isError = false;
        try {
            return operation.execute();
        } catch (RuntimeException e) {
            isError = true;
            throw e;
        } finally {
            try {
                finalizeTransaction(transactionManager, container, isError);
                IdentityUtilContext.setUtilContext(null);
                if (isNew) {
                    BroadleafRequestContext.setBroadleafRequestContext(null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static <T, G extends Throwable> T runOperationByIdentifier(IdentityOperation<T, G> operation, Site site, Catalog catalog) throws G {
        IdentityUtilContext context = new IdentityUtilContext();
        context.setIdentifier(site);
        IdentityUtilContext.setUtilContext(context);

        boolean isNew = initRequestContext(site, catalog);

        activateSession();

        try {
            return operation.execute();
        } catch (RuntimeException e) {
            throw e;
        } finally {
            IdentityUtilContext.setUtilContext(null);
            if (isNew) {
                BroadleafRequestContext.setBroadleafRequestContext(null);
            }
        }
    }

    public static <T, G extends Throwable> T runOperationByIdentifier(IdentityOperation<T, G> operation, Site site) throws G {
        return runOperationByIdentifier(operation, site, null);
    }

    public static <T, G extends Throwable> T runOperationAndIgnoreIdentifier(IdentityOperation<T, G> operation) throws G {
        boolean isNew = initRequestContext(null, null);

        activateSession();

        try {
            return operation.execute();
        } catch (RuntimeException e) {
            throw e;
        } finally {
            if (isNew) {
                BroadleafRequestContext.setBroadleafRequestContext(null);
            }
        }
    }
    
    public static <T, G extends Throwable> T runOperationAndIgnoreIdentifier(IdentityOperation<T, G> operation, 
            PlatformTransactionManager transactionManager) throws G {
        boolean isNew = initRequestContext(null, null);

        activateSession();

        TransactionContainer container = establishTransaction(transactionManager);
        boolean isError = false;
        try {
            return operation.execute();
        } catch (RuntimeException e) {
            isError = true;
            throw e;
        } finally {
            try {
                finalizeTransaction(transactionManager, container, isError);
                if (isNew) {
                    BroadleafRequestContext.setBroadleafRequestContext(null);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    private static boolean initRequestContext(Site site, Catalog catalog) {
        boolean isNew = false;
        BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext();
        if (requestContext == null) {
            requestContext = new BroadleafRequestContext();
            BroadleafRequestContext.setBroadleafRequestContext(requestContext);
            isNew = true;
        }
        if (site == null) {
            requestContext.setSite(null);
            requestContext.setIgnoreSite(true);
        } else {
            requestContext.setSite(site);
            requestContext.setIgnoreSite(false);
        }
        if (catalog == null) {
            requestContext.setCurrentCatalog(null);
        } else {
            requestContext.setCurrentCatalog(catalog);
        }
        return isNew;
    }

    private static void activateSession() {
        Map<Object, Object> resourceMap = TransactionSynchronizationManager.getResourceMap();
        for (Map.Entry<Object, Object> entry : resourceMap.entrySet()) {
            if (entry.getKey() instanceof EntityManagerFactory && entry.getValue() instanceof EntityManagerHolder) {
                ((HibernateEntityManager) ((EntityManagerHolder) entry.getValue()).getEntityManager()).getSession();
            }
        }
    }

    private static void finalizeTransaction(PlatformTransactionManager transactionManager, TransactionContainer
            container, boolean error) {<commit_msg>#1126 - Don't ignore site automatically in identity execution utils<commit_after>/*
 * #%L
 * BroadleafCommerce Common Libraries
 * %%
 * Copyright (C) 2009 - 2014 Broadleaf Commerce
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
package org.broadleafcommerce.common.util.tenant;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.site.domain.Catalog;
import org.broadleafcommerce.common.site.domain.Site;
import org.broadleafcommerce.common.util.TransactionUtils;
import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * The utility methods in this class provide a way to ignore the currently configured site/catalog contexts and instead
 * explicitly run operations in the specified context.
 * 
 * @author <NAME>
 */
public class IdentityExecutionUtils {

    private static final Log LOG = LogFactory.getLog(IdentityExecutionUtils.class);

    public static <T, G extends Throwable> T runOperationByIdentifier(IdentityOperation<T, G> operation, Site site, Catalog catalog,
                                                              PlatformTransactionManager transactionManager) throws G {
        IdentityUtilContext context = new IdentityUtilContext();
        context.setIdentifier(site);
        IdentityUtilContext.setUtilContext(context);

        boolean isNew = initRequestContext(site, catalog);

        activateSession();

        TransactionContainer container = establishTransaction(transactionManager);
        boolean isError = false;
        try {
            return operation.execute();
        } catch (RuntimeException e) {
            isError = true;
            throw e;
        } finally {
            try {
                finalizeTransaction(transactionManager, container, isError);
                IdentityUtilContext.setUtilContext(null);
                if (isNew) {
                    BroadleafRequestContext.setBroadleafRequestContext(null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static <T, G extends Throwable> T runOperationByIdentifier(IdentityOperation<T, G> operation, Site site, Catalog catalog) throws G {
        IdentityUtilContext context = new IdentityUtilContext();
        context.setIdentifier(site);
        IdentityUtilContext.setUtilContext(context);

        boolean isNew = initRequestContext(site, catalog);

        activateSession();

        try {
            return operation.execute();
        } catch (RuntimeException e) {
            throw e;
        } finally {
            IdentityUtilContext.setUtilContext(null);
            if (isNew) {
                BroadleafRequestContext.setBroadleafRequestContext(null);
            }
        }
    }

    public static <T, G extends Throwable> T runOperationByIdentifier(IdentityOperation<T, G> operation, Site site) throws G {
        return runOperationByIdentifier(operation, site, null);
    }

    public static <T, G extends Throwable> T runOperationAndIgnoreIdentifier(IdentityOperation<T, G> operation) throws G {
        boolean isNew = initRequestContext(null, null);
        boolean isIgnoringSite = BroadleafRequestContext.getBroadleafRequestContext().getIgnoreSite();
        BroadleafRequestContext.getBroadleafRequestContext().setIgnoreSite(true);

        activateSession();

        try {
            return operation.execute();
        } catch (RuntimeException e) {
            throw e;
        } finally {
            if (isNew) {
                BroadleafRequestContext.setBroadleafRequestContext(null);
            }
            BroadleafRequestContext.getBroadleafRequestContext().setIgnoreSite(isIgnoringSite);
        }
    }
    
    public static <T, G extends Throwable> T runOperationAndIgnoreIdentifier(IdentityOperation<T, G> operation, 
            PlatformTransactionManager transactionManager) throws G {
        boolean isNew = initRequestContext(null, null);
        boolean isIgnoringSite = BroadleafRequestContext.getBroadleafRequestContext().getIgnoreSite();
        BroadleafRequestContext.getBroadleafRequestContext().setIgnoreSite(true);

        activateSession();

        TransactionContainer container = establishTransaction(transactionManager);
        boolean isError = false;
        try {
            return operation.execute();
        } catch (RuntimeException e) {
            isError = true;
            throw e;
        } finally {
            try {
                finalizeTransaction(transactionManager, container, isError);
                if (isNew) {
                    BroadleafRequestContext.setBroadleafRequestContext(null);
                }
                BroadleafRequestContext.getBroadleafRequestContext().setIgnoreSite(isIgnoringSite);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    private static boolean initRequestContext(Site site, Catalog catalog) {
        boolean isNew = false;
        BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext();

        if (requestContext == null) {
            requestContext = new BroadleafRequestContext();
            BroadleafRequestContext.setBroadleafRequestContext(requestContext);
            isNew = true;
        }

        requestContext.setSite(site);
        requestContext.setCurrentCatalog(catalog);
        
        if (site != null) {
            requestContext.setIgnoreSite(false);
        }

        return isNew;
    }

    private static void activateSession() {
        Map<Object, Object> resourceMap = TransactionSynchronizationManager.getResourceMap();
        for (Map.Entry<Object, Object> entry : resourceMap.entrySet()) {
            if (entry.getKey() instanceof EntityManagerFactory && entry.getValue() instanceof EntityManagerHolder) {
                ((HibernateEntityManager) ((EntityManagerHolder) entry.getValue()).getEntityManager()).getSession();
            }
        }
    }

    private static void finalizeTransaction(PlatformTransactionManager transactionManager, TransactionContainer
            container, boolean error) {
{'fraction_non_alphanumeric': 0.07881386209360486, 'fraction_numerical': 0.002000714540907467, 'mean_word_length': 2.729283240074607, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3320784', 'n_tokens_mistral': 3304, 'n_tokens_neox': 3192, 'n_words': 854}