<commit_before>package com.kodedu.service;

import com.kodedu.component.DialogBuilder;
import com.kodedu.config.templates.AsciidocTemplateI;

import com.kodedu.helper.IOHelper;
import net.lingala.zip4j.ZipFile;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.*;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.nio.file.StandardOpenOption.*;

@Component
public class TemplateService {

    private Logger logger = LoggerFactory.getLogger(TemplateService.class);

	private final ThreadService threadService;

	public TemplateService(ThreadService threadService) {
		this.threadService = threadService;
	}

	/**
	 * Depending on the location of the template downloads it or copies the file. If
	 * it is a zip-archive it should be extracted. During the process no existing
	 * files should be overwritten.
	 * 
	 * @param targetDir
	 * @throws Exception
	 */
	public final void provide(AsciidocTemplateI template, Path targetDir) throws Exception {

		final var location = template.getLocation();
		var locationLowCase = location.toLowerCase();

		boolean isGitRepository = false;
		try {
			Collection<Ref> refs = Git.lsRemoteRepository()
					.setRemote(location)
					.call();
			if (Objects.nonNull(refs) && !refs.isEmpty()) {
				isGitRepository = true;
			}
		} catch (Exception e) {

		}

		Path locationPath = Paths.get(location);
		Path fileName = locationPath.getFileName();
		final Path[] filePath = {targetDir.resolve(fileName)};

		if(isGitRepository){
			if(Files.exists(filePath[0])){
				filePath[0] = getNewFolder(targetDir);
			}
			Files.createDirectories(filePath[0]);
			logger.info("Cloning template from {}", location);
			try (Git git = Git.cloneRepository()
					.setURI(locationLowCase)
					.setDirectory(filePath[0].toFile())
					.call();) {
			}
		} else if (locationLowCase.startsWith("http")) {
			logger.debug("Downloading template from: {}", location);
			Path zipPath = download(filePath[0], new URI(location));
			if (locationLowCase.endsWith(".zip")) {
				Path newFolder = getNewFolder(targetDir);
				Files.createDirectories(newFolder);
				logger.debug("Extracting zip: {}", zipPath);
				new ZipFile(zipPath.toFile()).extractAll(newFolder.toString());
				squeezeFolder(newFolder);
				IOHelper.deleteIfExists(zipPath);
			}
		} else {
			if (Files.exists(locationPath)) {
				logger.debug("Coping template from: {}", location);
				Path newFolder = getNewFolder(targetDir);
				Files.createDirectories(newFolder);
				IOHelper.copyDirectory(locationPath, newFolder);
			} else {
				logger.error("Template not exist in the provided path: {}", locationPath);
			}
		}

		logger.debug("Template provided: {}", location);
	}

	private void squeezeFolder(Path newFolder) throws IOException {
		try(Stream<Path> pathStream = Files.list(newFolder);){
			List<Path> extractedFiles = pathStream.collect(Collectors.toList());
			if (extractedFiles.size() == 1) {
				Path path = extractedFiles.get(0);
				if (Files.isDirectory(path)) {
					Path tempDirectory = Files.createTempDirectory("TemplateTempDir");
					Files.move(path, tempDirectory, StandardCopyOption.REPLACE_EXISTING);<commit_msg>Fix path resolving issue for Windows<commit_after>package com.kodedu.service;

import com.kodedu.component.DialogBuilder;
import com.kodedu.config.templates.AsciidocTemplateI;
import com.kodedu.helper.IOHelper;
import net.lingala.zip4j.ZipFile;
import org.apache.commons.io.FilenameUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.nio.file.StandardOpenOption.*;

@Component
public class TemplateService {

    private Logger logger = LoggerFactory.getLogger(TemplateService.class);

	private final ThreadService threadService;

	public TemplateService(ThreadService threadService) {
		this.threadService = threadService;
	}

	/**
	 * Depending on the location of the template downloads it or copies the file. If
	 * it is a zip-archive it should be extracted. During the process no existing
	 * files should be overwritten.
	 * 
	 * @param targetDir
	 * @throws Exception
	 */
	public final void provide(AsciidocTemplateI template, Path targetDir) throws Exception {

		final var location = template.getLocation();
		var locationLowCase = location.toLowerCase();

		boolean isGitRepository = false;
		try {
			Collection<Ref> refs = Git.lsRemoteRepository()
					.setRemote(location)
					.call();
			if (Objects.nonNull(refs) && !refs.isEmpty()) {
				isGitRepository = true;
			}
		} catch (Exception e) {

		}

		String fileName = FilenameUtils.getName(location);
		final Path[] filePath = {targetDir.resolve(fileName)};

		if(isGitRepository){
			if(Files.exists(filePath[0])){
				filePath[0] = getNewFolder(targetDir);
			}
			Files.createDirectories(filePath[0]);
			logger.info("Cloning template from {}", location);
			try (Git git = Git.cloneRepository()
					.setURI(locationLowCase)
					.setDirectory(filePath[0].toFile())
					.call();) {
			}
		} else if (locationLowCase.startsWith("http://") || locationLowCase.startsWith("https://")) {
			logger.debug("Downloading template from: {}", location);
			Path zipPath = download(filePath[0], new URI(location));
			if (locationLowCase.endsWith(".zip")) {
				Path newFolder = getNewFolder(targetDir);
				Files.createDirectories(newFolder);
				logger.debug("Extracting zip: {}", zipPath);
				new ZipFile(zipPath.toFile()).extractAll(newFolder.toString());
				squeezeFolder(newFolder);
				IOHelper.deleteIfExists(zipPath);
			}
		} else {
			Path locationPath = Paths.get(location);
			if (Files.exists(locationPath)) {
				logger.debug("Coping template from: {}", location);
				Path newFolder = getNewFolder(targetDir);
				Files.createDirectories(newFolder);
				IOHelper.copyDirectory(locationPath, newFolder);
			} else {
				logger.error("Template not exist in the provided path: {}", locationPath);
			}
		}

		logger.debug("Template provided: {}", location);
	}

	private void squeezeFolder(Path newFolder) throws IOException {
		try(Stream<Path> pathStream = Files.list(newFolder);){
			List<Path> extractedFiles = pathStream.collect(Collectors.toList());
			if (extractedFiles.size() == 1) {
				Path path = extractedFiles.get(0);
				if (Files.isDirectory(path)) {
					Path tempDirectory = Files.createTempDirectory("TemplateTempDir");
					Files.move(path, tempDirectory, StandardCopyOption.REPLACE_EXISTING);
{'fraction_non_alphanumeric': 0.12183729077462048, 'fraction_numerical': 0.002595043466978072, 'mean_word_length': 4.718100890207715, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6341276', 'n_tokens_mistral': 2595, 'n_tokens_neox': 2299, 'n_words': 495}