<commit_before>package eu.freme.eservices.epublishing;

import eu.freme.eservices.epublishing.exception.EPubCreationException;
import eu.freme.eservices.epublishing.exception.InvalidZipException;
import eu.freme.eservices.epublishing.exception.MissingMetadataException;
import eu.freme.eservices.epublishing.webservice.Metadata;
import org.apache.commons.io.FileUtils;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipInputStream;

/**
 *
 * @author <NAME> <<EMAIL>>
 */
public class EPublishingService {

    private static final File tempFolderPath = getTempFolder();
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(EPublishingService.class);

    public byte[] createEPUB(Metadata metadata, InputStream in) throws InvalidZipException, EPubCreationException, IOException, MissingMetadataException {
        // initialize the class that parses the input, and passes data to the EPUB creator
        File unzippedPath = File.createTempFile("freme_publishing", null, tempFolderPath);
        unzippedPath.deleteOnExit();    // doesn't work if not empty though...
        ByteArrayOutputStream bos;
                
        try (ZipInputStream zin = new ZipInputStream(in, StandardCharsets.UTF_8)) {
            Unzipper.unzip(zin, unzippedPath);

            EPubCreator creator = new EPubCreatorImpl(metadata, unzippedPath);

            // write the EPUB "file", in this case to bytes
            bos = new ByteArrayOutputStream();
            creator.onEnd(bos);
        } catch (IOException ex) {
            Logger.getLogger(EPublishingService.class.getName()).log(Level.SEVERE, null, ex);
            throw new InvalidZipException("Something went wrong with the provided Zip file. Make sure you are providing a valid Zip file.");
        } finally {
            FileUtils.deleteDirectory(unzippedPath);
        }
        
        return bos.toByteArray();
    }

    private static File getTempFolder() {
        File tmpFolder = new File(System.getProperty("java.io.tmpdir", "/tmp"));
        if (!testTmp(tmpFolder)) {
            logger.warn("Not enough permissions on default temporary folder " + tmpFolder + "!! Trying current working dir...");    // replace with logger
            // try the current working dir
            File workingDir = new File(System.getProperty("user.dir", "/tmp"));
            if (!testTmp(workingDir)) {
                logger.warn("Not enough permissions current working directory " + workingDir + "!! Temporary files will be written in " + tmpFolder + " and will exist until manually deleted !!");    // replace with logger
            } else {    // OK, make 'workingDir' the temporary folder<commit_msg>Lesson learned: a temporary created file is not a temporary created directory ;)<commit_after>package eu.freme.eservices.epublishing;

import eu.freme.eservices.epublishing.exception.EPubCreationException;
import eu.freme.eservices.epublishing.exception.InvalidZipException;
import eu.freme.eservices.epublishing.exception.MissingMetadataException;
import eu.freme.eservices.epublishing.webservice.Metadata;
import org.apache.commons.io.FileUtils;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipInputStream;

/**
 *
 * @author <NAME> <<EMAIL>>
 */
public class EPublishingService {

    private static final File tempFolderPath = getTempFolder();
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(EPublishingService.class);

    public byte[] createEPUB(Metadata metadata, InputStream in) throws InvalidZipException, EPubCreationException, IOException, MissingMetadataException {
        // initialize the class that parses the input, and passes data to the EPUB creator
        File unzippedPath = new File(tempFolderPath, "freme_epublishing_" + System.currentTimeMillis());
        FileUtils.forceDeleteOnExit(unzippedPath);
        ByteArrayOutputStream bos;
                
        try (ZipInputStream zin = new ZipInputStream(in, StandardCharsets.UTF_8)) {
            Unzipper.unzip(zin, unzippedPath);

            EPubCreator creator = new EPubCreatorImpl(metadata, unzippedPath);

            // write the EPUB "file", in this case to bytes
            bos = new ByteArrayOutputStream();
            creator.onEnd(bos);
        } catch (IOException ex) {
            Logger.getLogger(EPublishingService.class.getName()).log(Level.SEVERE, null, ex);
            throw new InvalidZipException("Something went wrong with the provided Zip file. Make sure you are providing a valid Zip file.");
        } finally {
            FileUtils.deleteDirectory(unzippedPath);
        }
        
        return bos.toByteArray();
    }

    private static File getTempFolder() {
        File tmpFolder = new File(System.getProperty("java.io.tmpdir", "/tmp"));
        if (!testTmp(tmpFolder)) {
            logger.warn("Not enough permissions on default temporary folder " + tmpFolder + "!! Trying current working dir...");    // replace with logger
            // try the current working dir
            File workingDir = new File(System.getProperty("user.dir", "/tmp"));
            if (!testTmp(workingDir)) {
                logger.warn("Not enough permissions current working directory " + workingDir + "!! Temporary files will be written in " + tmpFolder + " and will exist until manually deleted !!");    // replace with logger
            } else {    // OK, make 'workingDir' the temporary folder
{'fraction_non_alphanumeric': 0.09693964780304326, 'fraction_numerical': 0.0010258163788681826, 'mean_word_length': 3.2951541850220263, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, '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': '7321784', 'n_tokens_mistral': 1573, 'n_tokens_neox': 1539, 'n_words': 424}