Copy all the relations code templates into the destination directory read for processing

@throws DoctrineStaticMetaException
487958
private function copyRelationsTemplateToDestinationDirectory(): void
    {
        $this->pathHelper->copyTemplateDirectoryAndGetPath(
            $this->pathToProjectRoot,
            AbstractGenerator::RELATIONS_TEMPLATE_PATH,
            $this->destinationDirectory
        );
    }
1360165
protected void importRelations() {

        if (m_importedRelations.isEmpty()) {
            return;
        }

        m_report.println(Messages.get().container(Messages.RPT_START_IMPORT_RELATIONS_0), I_CmsReport.FORMAT_HEADLINE);

        int i = 0;
        Iterator<Entry<String, List<CmsRelation>>> it = m_importedRelations.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, List<CmsRelation>> entry = it.next();
            String resourcePath = entry.getKey();
            List<CmsRelation> relations = entry.getValue();

            m_report.print(
                org.opencms.report.Messages.get().container(
                    org.opencms.report.Messages.RPT_SUCCESSION_2,
                    String.valueOf(i + 1),
                    String.valueOf(m_importedRelations.size())),
                I_CmsReport.FORMAT_NOTE);

            m_report.print(
                Messages.get().container(
                    Messages.RPT_IMPORTING_RELATIONS_FOR_2,
                    resourcePath,
                    new Integer(relations.size())),
                I_CmsReport.FORMAT_NOTE);
            m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));

            boolean withErrors = false;
            Iterator<CmsRelation> itRelations = relations.iterator();
            while (itRelations.hasNext()) {
                CmsRelation relation = itRelations.next();
                try {
                    // Add the relation to the resource
                    m_cms.importRelation(
                        m_cms.getSitePath(relation.getSource(m_cms, CmsResourceFilter.ALL)),
                        m_cms.getSitePath(relation.getTarget(m_cms, CmsResourceFilter.ALL)),
                        relation.getType().getName());
                } catch (CmsException e) {
                    m_report.addWarning(e);
                    withErrors = true;
                    if (LOG.isWarnEnabled()) {
                        LOG.warn(e.getLocalizedMessage());
                    }
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
            if (!withErrors) {
                m_report.println(
                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                    I_CmsReport.FORMAT_OK);
            } else {
                m_report.println(
                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_FAILED_0),
                    I_CmsReport.FORMAT_ERROR);
            }
            i++;
        }

        m_report.println(Messages.get().container(Messages.RPT_END_IMPORT_RELATIONS_0), I_CmsReport.FORMAT_HEADLINE);
    }
1141825
def copy(self, contents=True):
        ''''''
        cp = connection(self._baseiri, self._attr_cls, self._logger)
        if contents: cp.add_many(self._relationships)

        return cp
1294146
protected function process()
    {

        // add the path => entity ID/store view code mapping
        $this->addPathEntityIdMapping($path = $this->getValue(ColumnKeys::PATH));
        $this->addPathStoreViewCodeMapping($path, $this->getSubject()->getStoreViewCode(StoreViewCodes::ADMIN));

        // temporary persist the path
        $this->setLastPath($path);
    }
445600
private void outputSubjectScheme() throws DITAOTException {
        try {
            final Map<URI, Set<URI>> graph = SubjectSchemeReader.readMapFromXML(new File(job.tempDir, FILE_NAME_SUBJECT_RELATION));

            final Queue<URI> queue = new LinkedList<>(graph.keySet());
            final Set<URI> visitedSet = new HashSet<>();

            final DocumentBuilder builder = XMLUtils.getDocumentBuilder();
            builder.setEntityResolver(CatalogUtils.getCatalogResolver());

            while (!queue.isEmpty()) {
                final URI parent = queue.poll();
                final Set<URI> children = graph.get(parent);

                if (children != null) {
                    queue.addAll(children);
                }
                if (ROOT_URI.equals(parent) || visitedSet.contains(parent)) {
                    continue;
                }
                visitedSet.add(parent);
                final File tmprel = new File(FileUtils.resolve(job.tempDir, parent) + SUBJECT_SCHEME_EXTENSION);
                final Document parentRoot;
                if (!tmprel.exists()) {
                    final URI src = job.getFileInfo(parent).src;
                    parentRoot = builder.parse(src.toString());
                } else {
                    parentRoot = builder.parse(tmprel);
                }
                if (children != null) {
                    for (final URI childpath: children) {
                        final Document childRoot = builder.parse(job.getInputFile().resolve(childpath.getPath()).toString());
                        mergeScheme(parentRoot, childRoot);
                        generateScheme(new File(job.tempDir, childpath.getPath() + SUBJECT_SCHEME_EXTENSION), childRoot);
                    }
                }

                //Output parent scheme
                generateScheme(new File(job.tempDir, parent.getPath() + SUBJECT_SCHEME_EXTENSION), parentRoot);
            }
        } catch (final RuntimeException e) {
            throw e;
        } catch (final Exception e) {
            logger.error(e.getMessage(), e) ;
            throw new DITAOTException(e);
        }

    }
1348781
protected function useRelationTraitInClass(string $classPath, string $traitPath): void
    {
        try {
            $class = PhpClass::fromFile($classPath);
        } catch (Error $e) {
            throw new DoctrineStaticMetaException(
                'PHP parsing error when loading class ' . $classPath . ': ' . $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        try {
            $trait = PhpTrait::fromFile($traitPath);
        } catch (Error $e) {
            throw new DoctrineStaticMetaException(
                'PHP parsing error when loading class ' . $classPath . ': ' . $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        $class->addTrait($trait);
        $this->codeHelper->generate($class, $classPath);
    }
225721
private void copyResources( List fileSets )
        throws MojoExecutionException
    {
        final String[] emptyStrArray = {};
        
        for ( Iterator it = fileSets.iterator(); it.hasNext(); )
        {
            FileSet fileSet = (FileSet) it.next();

            File resourceDirectory = new File( fileSet.getDirectory() );
            if ( !resourceDirectory.isAbsolute() )
            {
                resourceDirectory = new File( project.getBasedir(), resourceDirectory.getPath() );
            }

            if ( !resourceDirectory.exists() )
            {
                getLog().info( "Additional resource directory does not exist: " + resourceDirectory );
                continue;
            }

            DirectoryScanner scanner = new DirectoryScanner();

            scanner.setBasedir( resourceDirectory );
            if ( fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty() )
            {
                scanner.setIncludes( (String[]) fileSet.getIncludes().toArray( emptyStrArray ) );
            }
            else
            {
                scanner.setIncludes( DEFAULT_INCLUDES );
            }

            if ( fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty() )
            {
                scanner.setExcludes( (String[]) fileSet.getExcludes().toArray( emptyStrArray ) );
            }

            if (fileSet.isUseDefaultExcludes())
            {
                scanner.addDefaultExcludes();
            }

            scanner.scan();

            List includedFiles = Arrays.asList( scanner.getIncludedFiles() );

            getLog().info( "Copying " + includedFiles.size() + " additional resource"
                           + ( includedFiles.size() > 1 ? "s" : "" ) );

            for ( Iterator j = includedFiles.iterator(); j.hasNext(); )
            {
                String destination = (String) j.next();
                File source = new File( resourceDirectory, destination );
                File destinationFile = new File( buildDirectory, destination );

                if ( !destinationFile.getParentFile().exists() )
                {
                    destinationFile.getParentFile().mkdirs();
                }

                try
                {
                    FileUtils.copyFile(source, destinationFile);
                }
                catch ( IOException e )
                {
                    throw new MojoExecutionException( "Error copying additional resource " + source, e );
                }
            }
        }
    }
116814
protected function duplicateManyManyRelation($sourceObject, $destinationObject, $relation)
    {
        // Copy all components from source to destination
        $source = $sourceObject->getManyManyComponents($relation);
        $dest = $destinationObject->getManyManyComponents($relation);

        if ($source instanceof ManyManyList) {
            $extraFieldNames = $source->getExtraFields();
        } else {
            $extraFieldNames = [];
        }

        foreach ($source as $item) {
            // Merge extra fields
            $extraFields = [];
            foreach ($extraFieldNames as $fieldName => $fieldType) {
                $extraFields[$fieldName] = $item->getField($fieldName);
            }
            $dest->add($item, $extraFields);
        }
    }
263429
public function buildSymfonyContainer(array $server): void
    {
        if (true === $this->useCache && file_exists(self::SYMFONY_CACHE_PATH)) {
            /** @noinspection PhpIncludeInspection */
            require self::SYMFONY_CACHE_PATH;
            $this->setContainer(new \ProjectServiceContainer());

            return;
        }

        try {
            $container = new ContainerBuilder();
            $this->addConfiguration($container, $server);
            $container->compile();
            $this->setContainer($container);
            $dumper = new PhpDumper($container);
            file_put_contents(self::SYMFONY_CACHE_PATH, $dumper->dump());
        } catch (ServiceNotFoundException | InvalidArgumentException $e) {
            throw new DoctrineStaticMetaException(
                'Exception building the container: ' . $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
    }
865458
private <X extends Class, T extends Object> void populateMetadata(EntityMetadata metadata, Class<X> clazz,
            Map puProperties)
    {
        // process for metamodelImpl

        if (metadata.getPersistenceUnit() != null)
        {
            MetaModelBuilder<X, T> metaModelBuilder = kunderaMetadata.getApplicationMetadata().getMetaModelBuilder(
                    metadata.getPersistenceUnit());

            onBuildMetaModelSuperClass(clazz.getSuperclass(), metaModelBuilder);

            metaModelBuilder.process(clazz);

            for (Field f : clazz.getDeclaredFields())
            {
                if (f != null && !Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())
                        && !f.isAnnotationPresent(Transient.class))
                {
                    // construct metamodel.
                    metaModelBuilder.construct(clazz, f);

                    // on id attribute.
                    onIdAttribute(metaModelBuilder, metadata, clazz, f);

                    // determine if it is a column family or super column
                    // family.
                    onFamilyType(metadata, clazz, f);
                }
            }

            EntityType entityType = (EntityType) metaModelBuilder.getManagedTypes().get(metadata.getEntityClazz());

            validateAndSetId(metadata, clazz, metaModelBuilder);
            validateandSetEntityType(metadata, clazz, metaModelBuilder);
            MetadataUtils.onJPAColumnMapping(entityType, metadata);

            /* Scan for Relationship field */
            populateRelationMetaData(entityType, clazz, metadata);
        }
    }
121673
void populateRelationForM2M(Object entity, EntityMetadata entityMetadata, PersistenceDelegator delegator,
            Relation relation, Object relObject, Map<String, Object> relationsMap)
    {
        // For M-M relationship of Collection type, relationship entities are
        // always fetched from Join Table.
        if (relation.getPropertyType().isAssignableFrom(List.class)
                || relation.getPropertyType().isAssignableFrom(Set.class))
        {
            if (relation.isRelatedViaJoinTable() && (relObject == null || ProxyHelper.isProxyOrCollection(relObject)))
            {
                populateCollectionFromJoinTable(entity, entityMetadata, delegator, relation);
            }

        }
        else if (relation.getPropertyType().isAssignableFrom(Map.class))
        {
            if (relation.isRelatedViaJoinTable())
            {
                // TODO: Implement Map relationships via Join Table (not
                // supported as of now)
            }
            else
            {
                populateCollectionFromMap(entity, delegator, relation, relObject, relationsMap);
            }
        }
    }
672645
public function autodiscover(): void
    {
        $entityMappings = [];
        foreach ($this->fileSystem->getEntityDirectories() as $entityDirectory) {
            $namespace = $this->namespaceDetector->detectFromDirectory($entityDirectory);
            if (! $namespace) {
                continue;
            }

            $entityMappings[] = [
                'name' => $namespace, // required name
                'prefix' => $namespace,
                'type' => 'annotation',
                'dir' => $entityDirectory->getRealPath(),
                'is_bundle' => false, // performance
            ];
        }

        $xmlNamespaces = [];

        $directoryByNamespace = $this->resolveDirectoryByNamespace($this->fileSystem->getEntityXmlFiles());
        foreach ($directoryByNamespace as $namespace => $directory) {
            if (in_array($namespace, $xmlNamespaces, true)) {
                continue;
            }

            $xmlNamespaces[] = $namespace;

            $entityMappings[] = [
                'name' => $namespace, // required name
                'prefix' => $namespace,
                'type' => 'xml',
                'dir' => $directory,
                'is_bundle' => false,
            ];
        }

        if (! count($entityMappings)) {
            return;
        }

        // @see https://symfony.com/doc/current/reference/configuration/doctrine.html#mapping-entities-outside-of-a-bundle
        $this->containerBuilder->prependExtensionConfig('doctrine', [
            'orm' => ['mappings' => $entityMappings],
        ]);
    }
1315654
private void copyRelations(CmsDbContext dbc, CmsResource source, CmsResource target) throws CmsException {

        // copy relations all relations
        CmsObject cms = new CmsObject(getSecurityManager(), dbc.getRequestContext());
        Iterator<CmsRelation> itRelations = getRelationsForResource(
            dbc,
            source,
            CmsRelationFilter.TARGETS.filterNotDefinedInContent()).iterator();
        while (itRelations.hasNext()) {
            CmsRelation relation = itRelations.next();
            if (relation.getType().getCopyBehavior() == CopyBehavior.copy) {
                try {
                    CmsResource relTarget = relation.getTarget(cms, CmsResourceFilter.ALL);
                    addRelationToResource(dbc, target, relTarget, relation.getType(), true);
                } catch (CmsVfsResourceNotFoundException e) {
                    // ignore this broken relation
                    if (LOG.isWarnEnabled()) {
                        LOG.warn(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        // repair categories
        repairCategories(dbc, getProjectIdForContext(dbc), target);
    }
949934
def copy_templates(entry_point, py_entry_point, auto_write, output_dir):
    '''
    '''

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    scripts = []
    for f in os.listdir(bin_path()):
        ext = os.path.splitext(f)[-1]
        newline = NEWLINE_MAP.get(ext, '\n')
        template = bin_path(f)
        destination = output_dir + '/' + entry_point + ext
        scripts.append(destination)

        with io.open(template, 'r') as f:
            code = f.read()
        code = code.replace('{{entry_point}}', entry_point)
        code = code.replace('{{py_entry_point}}', py_entry_point)
        code = code.replace('{{auto_write}}', str(int(auto_write)))

        with io.open(destination, 'w', newline=newline) as f:
            f.write(code)

    return scripts
994499
public function validate(): Schema
    {
        $errors = $this->schemaValidator->validateMapping();
        if (!empty($errors)) {
            $allMetaData = $this->getAllMetaData();
            $mappingPath = __DIR__ . '/../../var/doctrineMapping.ser';
            file_put_contents($mappingPath, print_r($allMetaData, true));
            throw new DoctrineStaticMetaException(
                'Found errors in Doctrine mapping, mapping has been dumped to ' . $mappingPath . "\n\n" . print_r(
                    $errors,
                    true
                )
            );
        }

        return $this;
    }
292385
protected function compile()
    {
        $this->Template->start = $this->getRelatedStart($this);
        $this->Template->stop = $this->getRelatedStop($this);
        $this->Template->separators = $this->getRelatedSeparators($this);
        if ($this->getRelatedStart($this) !== null)
        {
            $this->Template->identifier = sprintf(self::$IDENTIFIER, $this->getRelatedStart($this)->id);
        }

        // Labels
        $this->Template->carouselPrevious = $GLOBALS['TL_LANG']['MSC']['carouselPrev'];
        $this->Template->carouselNext = $GLOBALS['TL_LANG']['MSC']['carouselNext'];

    }
1007416
private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) {
		MetaLookup metaLookup = mapped ? resourceMetaLookup : jpaMetaLookup;

		Class<? extends MetaDataObject> metaClass = mapped ? MetaJsonObject.class : MetaJpaDataObject.class;
		MetaDataObject meta = metaLookup.getMeta(resourceClass, metaClass);

		for (MetaAttribute attr : meta.getAttributes()) {
			if (!attr.isAssociation()) {
				continue;
			}
			MetaType attrType = attr.getType().getElementType();

			if (attrType instanceof MetaEntity) {
				// normal entity association
				Class<?> attrImplClass = attrType.getImplementationClass();
				JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass);

				// only include relations that are exposed as repositories
				if (attrConfig != null) {
					RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(attrImplClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig));
					context.addRepository(relationshipRepository);
				}
			} else if (attrType instanceof MetaResource) {
				Class<?> attrImplClass = attrType.getImplementationClass();
				JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass);
				if (attrConfig == null || attrConfig.getMapper() == null) {
					throw new IllegalStateException("no mapped entity for " + attrType.getName() + " reference by " + attr.getId() + " registered");
				}
				JpaRepositoryConfig<?> targetConfig = getRepositoryConfig(attrImplClass);
				Class<?> targetResourceClass = targetConfig.getResourceClass();

				RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(targetResourceClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig));
				context.addRepository(relationshipRepository);
			} else {
				throw new IllegalStateException("unable to process relation: " + attr.getId() + ", neither a entity nor a mapped entity is referenced");
			}
		}
	}