<commit_before>/*
 * #%L
 * Wisdom-Framework
 * %%
 * Copyright (C) 2013 - 2014 Wisdom Framework
 * %%
 * 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.wisdom.framework.jpa;

import org.apache.commons.io.IOUtils;
import org.apache.felix.ipojo.annotations.*;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.wiring.BundleWiring;
import org.wisdom.framework.jpa.model.Persistence;
import org.wisdom.framework.jpa.model.PersistenceUnitCachingType;
import org.wisdom.framework.jpa.model.PersistenceUnitValidationModeType;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * This class is the interface between the bridge (the manager) and the
 * Persistence Provider. It is used by the Persistence Provider to get all
 * context information. We create one of these for each persistence unit found
 * in a bundle.
 */
@Component
@Provides
public class PersistenceUnitComponent implements PersistenceUnitInfo {

    private static final String OSGI_UNIT_PROVIDER = "osgi.unit.provider";
    private static final String OSGI_UNIT_VERSION = "osgi.unit.version";
    private static final String OSGI_UNIT_NAME = "osgi.unit.name";

    private final Persistence.PersistenceUnit persistenceUnitXml;

    /**
     * Injected in the instance configuration.
     */
    private final PersistentBundle sourceBundle;
    private final String location;
    private final BundleContext bundleContext;


    /**
     * Filter injected in the instance configuration.
     */
    @Requires(optional = true, proxy = false, nullable = false, id = "jta-ds")
    private DataSource jtadatasource;

    /**
     * Filter injected in the instance configuration.
     */
    @Requires(optional = true, proxy = false, nullable = false, id = "ds")
    private DataSource nonjtadatasource;

    @Requires
    JPATransformer transformer;

    @Requires(proxy = false)
    PersistenceProvider provider;

    @Requires
    TransactionManager transactionManager;


    private ServiceRegistration<EntityManager> emRegistration;
    private ServiceRegistration<EntityManagerFactory> emfRegistration;

    /**
     * Create a new Persistence Unit Info
     *
     * @param bundle the source bundle
     * @param xml    The xml of the persistence unit
     */
    PersistenceUnitComponent(@Property(name = "bundle") PersistentBundle bundle,
                             @Property(name = "unit") Persistence.PersistenceUnit xml,
                             @Context BundleContext context) throws Exception {
        this.sourceBundle = bundle;
        this.persistenceUnitXml = xml;
        this.bundleContext = context;
        // Retrieve the location set while parsing the persistence unit.
        this.location = (String) getProperties().get("location");
    }

    /**
     * Shutdown this persistence unit
     */
    @Invalidate
    void shutdown() {
        if (emRegistration != null) {
            emRegistration.unregister();
        }
        if (emfRegistration != null) {
            emfRegistration.unregister();
        }
        if (transformer != null) {
            transformer.unregister(sourceBundle.bundle);
        }
    }

    @Validate
    public void start() {
        Map<String, Object> map = new HashMap<>();
        for (Persistence.PersistenceUnit.Properties.Property p :
                persistenceUnitXml.getProperties().getProperty()) {
            map.put(p.getName(), p.getValue());
        }

        if (isOpenJPA()) {
            map.put("openjpa.ManagedRuntime",
                    "invocation(TransactionManagerMethod=org.wisdom.framework.jpa.accessor" +
                            ".TransactionManagerAccessor.get)");
        }


        Hashtable<String, Object> properties = new Hashtable<>();
        properties.put(OSGI_UNIT_NAME, persistenceUnitXml.getName());
        properties.put(OSGI_UNIT_VERSION, sourceBundle.bundle.getVersion());
        properties.put(OSGI_UNIT_PROVIDER, provider.getClass().getName());
        properties.put("jpa.transaction.type", getTransactionType().toString());

        // If the unit set the transaction to RESOURCE_LOCAL, no JTA involved.
        if (persistenceUnitXml.getTransactionType() ==
                org.wisdom.framework.jpa.model.PersistenceUnitTransactionType.RESOURCE_LOCAL) {
            if (isOpenJPA()) {
                map.put("openjpa.TransactionMode", "false");
            }
            EntityManagerFactory emf = provider.createContainerEntityManagerFactory(this, map);
            emfRegistration = bundleContext.registerService(EntityManagerFactory.class, emf, properties);

            emRegistration = bundleContext.registerService(EntityManager.class,
                    emf.createEntityManager(), properties);
        } else {
            // JTA
            EntityManagerFactory emf = provider.createContainerEntityManagerFactory(this, map);
            emRegistration = bundleContext.registerService(EntityManager.class,
                    new TransactionalEntityManager(transactionManager, emf, this), properties);
            emfRegistration = bundleContext.registerService(EntityManagerFactory.class, emf, properties);
        }
    }

    private boolean isOpenJPA() {
        return provider.getClass().getName().contains("openjpa");
    }

    /**
     * Add a new transformer.
     *
     * @see javax.persistence.spi.PersistenceUnitInfo#addTransformer(javax.persistence.spi.ClassTransformer)
     */
    @Override
    public void addTransformer(ClassTransformer transformer) {
        try {
            this.transformer.register(sourceBundle.bundle, transformer);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /*<commit_msg>Remove useless try catch<commit_after>/*
 * #%L
 * Wisdom-Framework
 * %%
 * Copyright (C) 2013 - 2014 Wisdom Framework
 * %%
 * 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.wisdom.framework.jpa;

import org.apache.commons.io.IOUtils;
import org.apache.felix.ipojo.annotations.*;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.wiring.BundleWiring;
import org.wisdom.framework.jpa.model.Persistence;
import org.wisdom.framework.jpa.model.PersistenceUnitCachingType;
import org.wisdom.framework.jpa.model.PersistenceUnitValidationModeType;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * This class is the interface between the bridge (the manager) and the
 * Persistence Provider. It is used by the Persistence Provider to get all
 * context information. We create one of these for each persistence unit found
 * in a bundle.
 */
@Component
@Provides
public class PersistenceUnitComponent implements PersistenceUnitInfo {

    private static final String OSGI_UNIT_PROVIDER = "osgi.unit.provider";
    private static final String OSGI_UNIT_VERSION = "osgi.unit.version";
    private static final String OSGI_UNIT_NAME = "osgi.unit.name";

    private final Persistence.PersistenceUnit persistenceUnitXml;

    /**
     * Injected in the instance configuration.
     */
    private final PersistentBundle sourceBundle;
    private final String location;
    private final BundleContext bundleContext;


    /**
     * Filter injected in the instance configuration.
     */
    @Requires(optional = true, proxy = false, nullable = false, id = "jta-ds")
    private DataSource jtadatasource;

    /**
     * Filter injected in the instance configuration.
     */
    @Requires(optional = true, proxy = false, nullable = false, id = "ds")
    private DataSource nonjtadatasource;

    @Requires
    JPATransformer transformer;

    @Requires(proxy = false)
    PersistenceProvider provider;

    @Requires
    TransactionManager transactionManager;


    private ServiceRegistration<EntityManager> emRegistration;
    private ServiceRegistration<EntityManagerFactory> emfRegistration;

    /**
     * Create a new Persistence Unit Info
     *
     * @param bundle the source bundle
     * @param xml    The xml of the persistence unit
     */
    PersistenceUnitComponent(@Property(name = "bundle") PersistentBundle bundle,
                             @Property(name = "unit") Persistence.PersistenceUnit xml,
                             @Context BundleContext context) throws Exception {
        this.sourceBundle = bundle;
        this.persistenceUnitXml = xml;
        this.bundleContext = context;
        // Retrieve the location set while parsing the persistence unit.
        this.location = (String) getProperties().get("location");
    }

    /**
     * Shutdown this persistence unit
     */
    @Invalidate
    void shutdown() {
        if (emRegistration != null) {
            emRegistration.unregister();
        }
        if (emfRegistration != null) {
            emfRegistration.unregister();
        }
        if (transformer != null) {
            transformer.unregister(sourceBundle.bundle);
        }
    }

    @Validate
    public void start() {
        Map<String, Object> map = new HashMap<>();
        for (Persistence.PersistenceUnit.Properties.Property p :
                persistenceUnitXml.getProperties().getProperty()) {
            map.put(p.getName(), p.getValue());
        }

        if (isOpenJPA()) {
            map.put("openjpa.ManagedRuntime",
                    "invocation(TransactionManagerMethod=org.wisdom.framework.jpa.accessor" +
                            ".TransactionManagerAccessor.get)");
        }


        Hashtable<String, Object> properties = new Hashtable<>();
        properties.put(OSGI_UNIT_NAME, persistenceUnitXml.getName());
        properties.put(OSGI_UNIT_VERSION, sourceBundle.bundle.getVersion());
        properties.put(OSGI_UNIT_PROVIDER, provider.getClass().getName());
        properties.put("jpa.transaction.type", getTransactionType().toString());

        // If the unit set the transaction to RESOURCE_LOCAL, no JTA involved.
        if (persistenceUnitXml.getTransactionType() ==
                org.wisdom.framework.jpa.model.PersistenceUnitTransactionType.RESOURCE_LOCAL) {
            if (isOpenJPA()) {
                map.put("openjpa.TransactionMode", "false");
            }
            EntityManagerFactory emf = provider.createContainerEntityManagerFactory(this, map);
            emfRegistration = bundleContext.registerService(EntityManagerFactory.class, emf, properties);

            emRegistration = bundleContext.registerService(EntityManager.class,
                    emf.createEntityManager(), properties);
        } else {
            // JTA
            EntityManagerFactory emf = provider.createContainerEntityManagerFactory(this, map);
            emRegistration = bundleContext.registerService(EntityManager.class,
                    new TransactionalEntityManager(transactionManager, emf, this), properties);
            emfRegistration = bundleContext.registerService(EntityManagerFactory.class, emf, properties);
        }
    }

    private boolean isOpenJPA() {
        return provider.getClass().getName().contains("openjpa");
    }

    /**
     * Add a new transformer.
     *
     * @see javax.persistence.spi.PersistenceUnitInfo#addTransformer(javax.persistence.spi.ClassTransformer)
     */
    @Override
    public void addTransformer(ClassTransformer transformer) {
        this.transformer.register(sourceBundle.bundle, transformer);

    }

    /*
{'fraction_non_alphanumeric': 0.09151636606546426, 'fraction_numerical': 0.0017813404586951682, 'mean_word_length': 3.0768532526475036, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 8}, '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': '987185', 'n_tokens_mistral': 3511, 'n_tokens_neox': 3421, 'n_words': 882}