<commit_before>/*
 * Copyright 2008-2009 the original author or authors.
 *
 * 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.
 */
package org.broadleafcommerce.profile.extensibility.jpa;

import java.lang.instrument.UnmodifiableClassException;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.persistence.spi.PersistenceUnitInfo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.profile.extensibility.jpa.convert.BroadleafClassTransformer;
import org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager;
import org.springframework.orm.jpa.persistenceunit.Jpa2PersistenceUnitInfoDecorator;
import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
import org.springframework.orm.jpa.persistenceunit.SmartPersistenceUnitInfo;
import org.springframework.util.ClassUtils;

/**
 * Merges jars, class names and mapping file names from several persistence.xml files. The
 * MergePersistenceUnitManager will continue to keep track of individual persistence unit
 * names (including individual data sources). When a specific PersistenceUnitInfo is requested
 * by unit name, the appropriate PersistenceUnitInfo is returned with modified jar files
 * urls, class names and mapping file names that include the comprehensive collection of these
 * values from all persistence.xml files.
 * 
 * 
 * @author jfischer, jjacobs
 */
public class MergePersistenceUnitManager extends DefaultPersistenceUnitManager {

	private static final Log LOG = LogFactory.getLog(MergePersistenceUnitManager.class);
	
    protected HashMap<String, PersistenceUnitInfo> mergedPus = new HashMap<String, PersistenceUnitInfo>();
    protected final boolean jpa2ApiPresent = ClassUtils.hasMethod(PersistenceUnitInfo.class, "getSharedCacheMode");
    protected List<BroadleafClassTransformer> classTransformers = new ArrayList<BroadleafClassTransformer>();

    protected PersistenceUnitInfo getMergedUnit(String persistenceUnitName, MutablePersistenceUnitInfo newPU) {
        if (!mergedPus.containsKey(persistenceUnitName)) {
        	PersistenceUnitInfo puiToStore = newPU;
			if (jpa2ApiPresent) {
				puiToStore = (PersistenceUnitInfo) Proxy.newProxyInstance(SmartPersistenceUnitInfo.class.getClassLoader(),
						new Class[] {SmartPersistenceUnitInfo.class}, new Jpa2PersistenceUnitInfoDecorator(newPU));
			}
			for (BroadleafClassTransformer transformer : classTransformers) {
				try {
					puiToStore.addTransformer(transformer);
				} catch (IllegalStateException e) {
					LOG.warn("A BroadleafClassTransformer is configured for this persistence unit, but Spring reported a problem (likely that a LoadTimeWeaver is not registered). As a result, the Broadleaf Commerce ClassTransformer ("+transformer.getClass().getName()+") is not being registered with the persistence unit.", e);
				}
			}
            mergedPus.put(persistenceUnitName, puiToStore);
        }
        return mergedPus.get(persistenceUnitName);
    }
    
    @SuppressWarnings("rawtypes")
	@Override
	public void preparePersistenceUnitInfos() {
		super.preparePersistenceUnitInfos();
		/*
    	 * Re-transform any classes that were possibly loaded previously before our class transformers were registered
    	 */
    	try {
    		if (BroadleafLoadTimeWeaver.isInstrumentationAvailable()) {
    			if (BroadleafLoadTimeWeaver.getInstrumentation().isRetransformClassesSupported()) {
	    			List<Class> filteredClasses = new ArrayList<Class>();
	    			Class[] initiatedClasses = BroadleafLoadTimeWeaver.getInstrumentation().getInitiatedClasses(getClass().getClassLoader());
	    			for (Class clazz : initiatedClasses) {
	    				if (BroadleafLoadTimeWeaver.getInstrumentation().isModifiableClass(clazz)) {
	    					filteredClasses.add(clazz);
	    				}
	    			}
	    			BroadleafLoadTimeWeaver.getInstrumentation().retransformClasses(filteredClasses.toArray(new Class[]{}));
    			} else {
    				LOG.warn("The JVM instrumentation is reporting that retransformation of classes is not supported. This feature is required for dependable class transformation with Broadleaf. Have you made sure to specify the broadleaf-instrument jar as a javaagent parameter for your JVM?");
    			}
    		}
    	} catch (UnmodifiableClassException e) {
			throw new RuntimeException(e);
		}
	}

    @Override<commit_msg>refactored a bit to make class re-transformation more efficient<commit_after>/*
 * Copyright 2008-2009 the original author or authors.
 *
 * 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.
 */
package org.broadleafcommerce.profile.extensibility.jpa;

import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.persistence.spi.PersistenceUnitInfo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.profile.extensibility.jpa.convert.BroadleafClassTransformer;
import org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager;
import org.springframework.orm.jpa.persistenceunit.Jpa2PersistenceUnitInfoDecorator;
import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
import org.springframework.orm.jpa.persistenceunit.SmartPersistenceUnitInfo;
import org.springframework.util.ClassUtils;

/**
 * Merges jars, class names and mapping file names from several persistence.xml files. The
 * MergePersistenceUnitManager will continue to keep track of individual persistence unit
 * names (including individual data sources). When a specific PersistenceUnitInfo is requested
 * by unit name, the appropriate PersistenceUnitInfo is returned with modified jar files
 * urls, class names and mapping file names that include the comprehensive collection of these
 * values from all persistence.xml files.
 * 
 * 
 * @author jfischer, jjacobs
 */
public class MergePersistenceUnitManager extends DefaultPersistenceUnitManager {

	private static final Log LOG = LogFactory.getLog(MergePersistenceUnitManager.class);
	
    protected HashMap<String, PersistenceUnitInfo> mergedPus = new HashMap<String, PersistenceUnitInfo>();
    protected final boolean jpa2ApiPresent = ClassUtils.hasMethod(PersistenceUnitInfo.class, "getSharedCacheMode");
    protected List<BroadleafClassTransformer> classTransformers = new ArrayList<BroadleafClassTransformer>();

    protected PersistenceUnitInfo getMergedUnit(String persistenceUnitName, MutablePersistenceUnitInfo newPU) {
        if (!mergedPus.containsKey(persistenceUnitName)) {
        	PersistenceUnitInfo puiToStore = newPU;
			if (jpa2ApiPresent) {
				puiToStore = (PersistenceUnitInfo) Proxy.newProxyInstance(SmartPersistenceUnitInfo.class.getClassLoader(),
						new Class[] {SmartPersistenceUnitInfo.class}, new Jpa2PersistenceUnitInfoDecorator(newPU));
			}
            mergedPus.put(persistenceUnitName, puiToStore);
        }
        return mergedPus.get(persistenceUnitName);
    }
    
	@Override
	public void preparePersistenceUnitInfos() {
		super.preparePersistenceUnitInfos();
		try {
			List<Class<?>> managedClassList = new ArrayList<Class<?>>();
			for (PersistenceUnitInfo pui : mergedPus.values()) {
				for (BroadleafClassTransformer transformer : classTransformers) {
					try {
						pui.addTransformer(transformer);
					} catch (IllegalStateException e) {
						LOG.warn("A BroadleafClassTransformer is configured for this persistence unit, but Spring reported a problem (likely that a LoadTimeWeaver is not registered). As a result, the Broadleaf Commerce ClassTransformer ("+transformer.getClass().getName()+") is not being registered with the persistence unit.", e);
					}
				}
			}
			for (PersistenceUnitInfo pui : mergedPus.values()) {
				for (String managedClassName : pui.getManagedClassNames()) {
					Class<?> temp = Class.forName(managedClassName, true, getClass().getClassLoader());
					if (!managedClassList.contains(temp)) {
						managedClassList.add(temp);
					}
				}
			}
			
			/*
	    	 * Re-transform any classes that were possibly loaded previously before our class transformers were registered
	    	 */
    		if (BroadleafLoadTimeWeaver.isInstrumentationAvailable()) {
    			if (BroadleafLoadTimeWeaver.getInstrumentation().isRetransformClassesSupported()) {
	    			List<Class<?>> filteredClasses = new ArrayList<Class<?>>();
	    			for (Class<?> clazz : managedClassList) {
	    				if (BroadleafLoadTimeWeaver.getInstrumentation().isModifiableClass(clazz)) {
	    					filteredClasses.add(clazz);
	    				}
	    			}
	    			BroadleafLoadTimeWeaver.getInstrumentation().retransformClasses(filteredClasses.toArray(new Class[]{}));
    			} else {
    				LOG.warn("The JVM instrumentation is reporting that retransformation of classes is not supported. This feature is required for dependable class transformation with Broadleaf. Have you made sure to specify the broadleaf-instrument jar as a javaagent parameter for your JVM?");
    			}
    		}
    	} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

    @Override
{'fraction_non_alphanumeric': 0.08041821379714677, 'fraction_numerical': 0.003126832128200117, 'mean_word_length': 4.62981298129813, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3963333', 'n_tokens_mistral': 2913, 'n_tokens_neox': 2708, 'n_words': 775}