One time initialization for persistence unit metadata.

@param persistenceUnit
Persistence Unit/ Comma separated persistence units
967287
private void configurePersistenceUnit(PersistenceUnitInfo puInfo, Map props)
    {
        // Invoke Persistence unit MetaData
        if (puInfo.getPersistenceUnitName() == null)
        {
            throw new KunderaException("Persistence unit name should not be null");
        }
        if (logger.isInfoEnabled())
        {
            logger.info("Loading Persistence Unit MetaData For Persistence Unit(s) {}.",
                    puInfo.getPersistenceUnitName());
        }

        String[] persistenceUnits = puInfo.getPersistenceUnitName().split(Constants.PERSISTENCE_UNIT_SEPARATOR);

        new PersistenceUnitConfiguration(props, kunderaMetadata, persistenceUnits).configure(puInfo);
    }
128589
private static void initialize(final boolean _restart)
        throws CacheReloadException
    {
        if (InfinispanCache.get().exists(IndexDefinition.UUIDCACHE)) {
            if (_restart) {
                InfinispanCache.get().<UUID, IndexDefinition>getCache(IndexDefinition.UUIDCACHE).clear();
            }
        } else {
            InfinispanCache.get().<UUID, Type>getCache(IndexDefinition.UUIDCACHE).addListener(new CacheLogListener(
                            IndexDefinition.LOG));
        }
    }
826780
public static void initializeMetadata()
    {
        // TODO: merge inside meta API.
        DbConn cnx = null;
        try
        {
            cnx = Helpers.getNewDbSession();
            Helpers.updateConfiguration(cnx);
            cnx.commit();
        }
        catch (Exception e)
        {
            throw new JqmRuntimeException("Could not set metadata", e);
        }
        finally
        {
            Helpers.closeQuietly(cnx);
        }
    }
1179018
private static PersistenceUnit newPersistenceUnit(final String fJndiName, final String fUnitName)
    {
        return new PersistenceUnit()
        {
            @Override
            public String name()
            {
                return fJndiName;
            }

            @Override
            public Class<? extends Annotation> annotationType()
            {
                return javax.persistence.PersistenceUnit.class;
            }

            @Override
            public String unitName()
            {
                return fUnitName;
            }

            @Override
            public String toString()
            {
                return "JPA.PersistenceUnit(name=" + fJndiName +
                       ", unitName=" + fUnitName + ")";
            }
        };
    }
1203019
static final Properties getProperties(final KunderaMetadata kunderaMetadata, final String persistenceUnit)
    {
        PersistenceUnitMetadata persistenceUnitMetadatata = kunderaMetadata.getApplicationMetadata()
                .getPersistenceUnitMetadata(persistenceUnit);
        Properties props = persistenceUnitMetadatata.getProperties();
        return props;
    }
887340
private void loadEntityMetadata(String persistenceUnit)
    {
        if (persistenceUnit == null)
        {
            throw new IllegalArgumentException(
                    "Must have a persistenceUnitName in order to load entity metadata, you provided :"
                            + persistenceUnit);
        }

        Map<String, PersistenceUnitMetadata> persistentUnitMetadataMap = kunderaMetadata.getApplicationMetadata()
                .getPersistenceUnitMetadataMap();

        /** Classes to scan */
        List<String> classesToScan;
        URL[] resources = null;
        String client = null;
        List<URL> managedURLs = null;
        if (persistentUnitMetadataMap == null || persistentUnitMetadataMap.isEmpty())
        {
            log.error("It is necessary to load Persistence Unit metadata  for persistence unit " + persistenceUnit
                    + " first before loading entity metadata.");
            throw new MetamodelLoaderException("load Persistence Unit metadata  for persistence unit "
                    + persistenceUnit + " first before loading entity metadata.");
        }
        else
        {
            PersistenceUnitMetadata puMetadata = persistentUnitMetadataMap.get(persistenceUnit);
            classesToScan = puMetadata.getManagedClassNames();
            managedURLs = puMetadata.getManagedURLs();
            client = getClientFactoryName(persistenceUnit);
        }

        /*
         * Check whether Classes to scan was provided into persistence.xml If
         * yes, load them. Otherwise load them from classpath/ context path
         */
        Reader reader;
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        if (classesToScan == null || classesToScan.isEmpty())
        {
            log.info("No class to scan for persistence unit " + persistenceUnit
                    + ". Entities will be loaded from classpath/ context-path");
            // Entity metadata is not related to any PU, and hence will be
            // stored at common place
            // persistenceUnit = Constants.COMMON_ENTITY_METADATAS;

            // Check whether all common entity metadata have already been loaded
            if (appMetadata.getMetamodelMap().get(persistenceUnit) != null)
            {
                log.info("All common entitity metadata already loaded, nothing need to be done");
                return;
            }

            reader = new ClasspathReader();
            // resources = reader.findResourcesByClasspath();
        }
        else
        {
            reader = new ClasspathReader(classesToScan);
            // resources = reader.findResourcesByContextLoader();
        }

        InputStream[] iStreams = null;
        PersistenceUnitMetadata puMetadata = persistentUnitMetadataMap.get(persistenceUnit);
        if (this.getClass().getClassLoader() instanceof URLClassLoader && !puMetadata.getExcludeUnlistedClasses())
        {
            URL[] managedClasses = reader.findResources();
            if (managedClasses != null)
            {
                List<URL> managedResources = Arrays.asList(managedClasses);
                managedURLs.addAll(managedResources);
            }
        }
        else
        {
            iStreams = reader.findResourcesAsStream();
        }

        if (managedURLs != null)
        {
            resources = managedURLs.toArray(new URL[] {});
        }

        // All entities to load should be annotated with @Entity
        reader.addValidAnnotations(Entity.class.getName());

        Metamodel metamodel = appMetadata.getMetamodel(persistenceUnit);
        if (metamodel == null)
        {
            metamodel = new MetamodelImpl();
        }

        Map<String, EntityMetadata> entityMetadataMap = ((MetamodelImpl) metamodel).getEntityMetadataMap();
        Map<String, Class<?>> entityNameToClassMap = ((MetamodelImpl) metamodel).getEntityNameToClassMap();
        Map<String, List<String>> puToClazzMap = new HashMap<String, List<String>>();
        Map<String, IdDiscriptor> entityNameToKeyDiscriptorMap = new HashMap<String, IdDiscriptor>();
        List<Class<?>> classes = new ArrayList<Class<?>>();
        if (resources != null && resources.length > 0)
        {
            for (URL resource : resources)
            {
                try
                {
                    ResourceIterator itr = reader.getResourceIterator(resource, reader.getFilter());

                    InputStream is = null;
                    while ((is = itr.next()) != null)
                    {
                        classes.addAll(scanClassAndPutMetadata(is, reader, entityMetadataMap, entityNameToClassMap,
                                persistenceUnit, client, puToClazzMap, entityNameToKeyDiscriptorMap));
                    }
                }
                catch (IOException e)
                {
                    log.error("Error while retrieving and storing entity metadata. Details:", e);
                    throw new MetamodelLoaderException("Error while retrieving and storing entity metadata");

                }
            }
        }
        else if (iStreams != null)
        {
            try
            {
                for (InputStream is : iStreams)
                {
                    try
                    {
                        classes.addAll(scanClassAndPutMetadata(is, reader, entityMetadataMap, entityNameToClassMap,
                                persistenceUnit, client, puToClazzMap, entityNameToKeyDiscriptorMap));
                    }
                    finally
                    {
                        if (is != null)
                        {
                            is.close();
                        }
                    }
                }
            }
            catch (IOException e)
            {
                log.error("Error while retrieving and storing entity metadata. Details:", e);
                throw new MetamodelLoaderException("Error while retrieving and storing entity metadata, Caused by : .",
                        e);

            }
        }
        ((MetamodelImpl) metamodel).setEntityMetadataMap(entityMetadataMap);
        appMetadata.getMetamodelMap().put(persistenceUnit, metamodel);
        appMetadata.setClazzToPuMap(puToClazzMap);
        ((MetamodelImpl) metamodel).addKeyValues(entityNameToKeyDiscriptorMap);
        // assign JPA metamodel.
        ((MetamodelImpl) metamodel).assignEmbeddables(kunderaMetadata.getApplicationMetadata()
                .getMetaModelBuilder(persistenceUnit).getEmbeddables());
        ((MetamodelImpl) metamodel).assignManagedTypes(kunderaMetadata.getApplicationMetadata()
                .getMetaModelBuilder(persistenceUnit).getManagedTypes());
        ((MetamodelImpl) metamodel).assignMappedSuperClass(kunderaMetadata.getApplicationMetadata()
                .getMetaModelBuilder(persistenceUnit).getMappedSuperClassTypes());
    }
167010
@Override
    protected Client<?> instantiateClient(String persistenceUnit)
    {
        return new DSClient(this, persistenceUnit, externalProperties, kunderaMetadata, reader, timestampGenerator);
    }
27272
private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException
    {
        String puLocation = (String) (externalPropertyMap != null
                && externalPropertyMap.get(Constants.PERSISTENCE_UNIT_LOCATIION) != null ? externalPropertyMap
                .get(Constants.PERSISTENCE_UNIT_LOCATIION) : Constants.DEFAULT_PERSISTENCE_UNIT_LOCATIION);

        Enumeration<URL> xmls = null;
        try
        {
            xmls = this.getClass().getClassLoader().getResources(puLocation);
        }
        catch (IOException ioex)
        {
            log.warn("Error while loading persistence.xml, Caused by: {}.", ioex);
        }

        if (xmls == null || !xmls.hasMoreElements())
        {
            log.error("Could not find any META-INF/persistence.xml file in the classpath");
            throw new InvalidConfigurationException("Could not find any META-INF/persistence.xml file in the classpath");
        }

        Set<String> persistenceUnitNames = new HashSet<String>();
        Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();
        while (xmls.hasMoreElements())
        {
            URL url = xmls.nextElement();

            log.trace("Analysing persistence.xml: " + url);
            List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url, persistenceUnits, 
                    PersistenceUnitTransactionType.RESOURCE_LOCAL);

            // Pick only those that have Kundera Provider
            for (PersistenceUnitMetadata metadata : metadataFiles)
            {
                // check for unique names
                if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))
                {
                    if (log.isWarnEnabled())
                    {
                        log.warn("Duplicate persistence-units for name: " + metadata.getPersistenceUnitName()
                                + ". verify your persistence.xml file");
                    }
                }

                // check for provider
                if (metadata.getPersistenceProviderClassName() == null
                        || PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))
                {
                    persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);
                }

                // add to check for duplicate persistence unit.
                persistenceUnitNames.add(metadata.getPersistenceUnitName());
            }
        }
        return persistenceUnitMap;
    }
384076
@Override
    public void configure()
    {
        log.info("Loading Metadata from persistence.xml ...");

        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();

        try
        {
            Map<String, PersistenceUnitMetadata> metadatas = findPersistenceMetadatas();
            for (String persistenceUnit : persistenceUnits)
            {
                if (!metadatas.containsKey(persistenceUnit))
                {
                    log.error("Unconfigured persistence unit: " + persistenceUnit
                            + " please validate with persistence.xml");
                    throw new PersistenceUnitConfigurationException("Invalid persistence unit: " + persistenceUnit
                            + " provided");
                }
            }
            log.info("Finishing persistence unit metadata configuration ...");
            appMetadata.addPersistenceUnitMetadata(metadatas);
        }
        catch (InvalidConfigurationException icex)
        {
            log.error("Error occurred during persistence unit configuration, Caused by: .", icex);
            throw new PersistenceLoaderException(icex);
        }
    }
258530
@PostConstruct
    public void init() {
        log.debug("Registering JVM gauges");
        metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
        metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
        metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
        metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
        metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(getPlatformMBeanServer()));
        metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
        metricRegistry.register(PROP_METRIC_REG_OS, new OperatingSystemGaugeSet(getOperatingSystemMXBean()));

        if (jhipsterProperties.getMetrics().getJmx().isEnabled()) {
            log.debug("Initializing Metrics JMX reporting");
            JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
            jmxReporter.start();
        }
        if (jhipsterProperties.getMetrics().getLogs().isEnabled()) {
            log.info("Initializing Metrics Log reporting");
            Marker metricsMarker = MarkerFactory.getMarker("metrics");
            final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
                .outputTo(LoggerFactory.getLogger("metrics"))
                .markWith(metricsMarker)
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();
            reporter.start(jhipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
        }
    }
1283334
@Override
    public void initialize(Map<String, Object> puProperties)
    {
        reader = new KuduDBEntityReader(kunderaMetadata);
        setExternalProperties(puProperties);
        initializePropertyReader();
        PersistenceUnitMetadata pum = kunderaMetadata.getApplicationMetadata()
                .getPersistenceUnitMetadata(getPersistenceUnit());

        Properties pumProps = pum.getProperties();

        if (puProperties != null)
        {
            pumProps.putAll(puProperties);
        }

        String kuduMasterHost = (String) pumProps.getProperty("kundera.nodes");

        String kuduMasterPort = (String) pumProps.getProperty("kundera.port");

        if (kuduMasterHost == null || kuduMasterPort == null)
        {
            throw new KunderaException("Hostname/IP or Port is null.");
        }

        kuduClient = new KuduClient.KuduClientBuilder(kuduMasterHost + ":" + kuduMasterPort).build();
    }
1294904
private Client discoverClient(String persistenceUnit)
    {
        if (logger.isInfoEnabled())
        {
            logger.info("Returning client instance for persistence unit {}.", persistenceUnit);
        }

        ClientFactory clientFactory = ((EntityManagerFactoryImpl) getEntityManagerFactory())
                .getClientFactory(persistenceUnit);
        if (clientFactory != null)
        {
            return clientFactory.getClientInstance();
        }
        throw new ClientResolverException("No client configured for persistence unit " + persistenceUnit + ".");
    }
1116621
public void init() {
        if (incNestingCount() > 1) {
            return;
        }
        SessionFactory sf = getSessionFactory();
        if (sf == null) {
            return;
        }
        if (TransactionSynchronizationManager.hasResource(sf)) {
            // Do not modify the Session: just set the participate flag.
            setParticipate(true);
        }
        else {
            setParticipate(false);
            LOG.debug("Opening single Hibernate session in HibernatePersistenceContextInterceptor");
            Session session = getSession();
            HibernateRuntimeUtils.enableDynamicFilterEnablerIfPresent(sf, session);
            TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
        }
    }
951755
@Override
    public AbstractLessLockingUniversalSingleStorageJdbcQueue init() throws Exception {
        super.init();

        if (getMessageFactory() == null) {
            setMessageFactory(UniversalIdIntQueueMessageFactory.INSTANCE);
        }

        SQL_COUNT = MessageFormat.format(SQL_COUNT, getTableName());
        SQL_COUNT_EPHEMERAL = MessageFormat.format(SQL_COUNT_EPHEMERAL, getTableNameEphemeral());

        return this;
    }
684545
public void initServices() {
    initService(repositoryService);
    initService(runtimeService);
    initService(historyService);
    initService(taskService);
    initService(managementService);
    initService(dynamicBpmnService);
  }
1231674
@Override
    public void initializeApplication(ApplicationDefinition oldAppDef,
                                      ApplicationDefinition appDef) {
        checkServiceState();
        verifyApplicationCFs(oldAppDef, appDef);
    }
315972
public static PersistenceUnitMetadata getPersistenceUnitMetadata(final KunderaMetadata kunderaMetadata,
            String persistenceUnit)
    {
        if (persistenceUnit != null && kunderaMetadata != null)
        {
            return kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit);
        }
        return null;
    }