Search in sources :

Example 1 with PreferencesException

use of ugh.exceptions.PreferencesException in project goobi-workflow by intranda.

the class Metadaten method XMLlesenStart.

/**
 * Metadaten Einlesen
 *
 * @throws ReadException
 * @throws InterruptedException
 * @throws IOException
 * @throws PreferencesException ============================================================ == ==
 * @throws DAOException
 * @throws SwapException
 * @throws WriteException
 */
public String XMLlesenStart() throws ReadException, IOException, InterruptedException, PreferencesException, SwapException, DAOException, WriteException {
    currentRepresentativePage = "";
    this.myPrefs = this.myProzess.getRegelsatz().getPreferences();
    enablePageArea = myPrefs.getDocStrctTypeByName("area") != null;
    this.modusHinzufuegen = false;
    this.modusHinzufuegenPerson = false;
    this.modusStrukturelementVerschieben = false;
    this.modusCopyDocstructFromOtherProcess = false;
    this.currentTifFolder = null;
    readAllTifFolders();
    /*
         * -------------------------------- Dokument einlesen --------------------------------
         */
    this.gdzfile = this.myProzess.readMetadataFile();
    if (gdzfile == null) {
        return null;
    }
    this.document = this.gdzfile.getDigitalDocument();
    this.document.addAllContentFiles();
    this.metahelper = new MetadatenHelper(this.myPrefs, this.document);
    this.imagehelper = new MetadatenImagesHelper(this.myPrefs, this.document);
    /*
         * -------------------------------- Das Hauptelement ermitteln --------------------------------
         */
    this.logicalTopstruct = this.document.getLogicalDocStruct();
    // this exception needs some serious feedback because data is corrupted
    if (this.logicalTopstruct == null) {
        throw new ReadException(Helper.getTranslation("metaDataError"));
    }
    // initialize page area editor
    this.pageAreaManager = new PageAreaManager(this.myPrefs, this.document);
    checkImageNames();
    retrieveAllImages();
    // check filenames, correct them
    // initialize image list
    numberOfImagesPerPage = ConfigurationHelper.getInstance().getMetsEditorNumberOfImagesPerPage();
    thumbnailSizeInPixel = ConfigurationHelper.getInstance().getMetsEditorThumbnailSize();
    pageNo = 0;
    imageIndex = 0;
    loadCurrentImages(true);
    if (this.document.getPhysicalDocStruct().getAllMetadata() != null && this.document.getPhysicalDocStruct().getAllMetadata().size() > 0) {
        List<Metadata> lstMetadata = this.document.getPhysicalDocStruct().getAllMetadata();
        for (Metadata md : lstMetadata) {
            if (md.getType().getName().equals("_representative")) {
                try {
                    Integer value = Integer.valueOf(md.getValue());
                    currentRepresentativePage = String.valueOf(value);
                    updateRepresentativePage();
                } catch (Exception e) {
                }
            }
        }
        DocStruct docstruct = logicalTopstruct;
        if (docstruct.getType().isAnchor()) {
            docstruct = docstruct.getAllChildren().get(0);
        }
        lstMetadata = docstruct.getAllMetadata();
        if (lstMetadata != null) {
            for (Metadata md : lstMetadata) {
                if (md.getType().getName().equals("_directionRTL")) {
                    try {
                        Boolean value = Boolean.valueOf(md.getValue());
                        this.pagesRTL = value;
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
    createDefaultValues(this.logicalTopstruct);
    MetadatenalsBeanSpeichern(this.logicalTopstruct);
    MetadatenalsTree3Einlesen1(this.tree3, this.logicalTopstruct, false);
    physicalTopstruct = document.getPhysicalDocStruct();
    currentTopstruct = logicalTopstruct;
    if (this.nurLesenModus || allImages.isEmpty()) {
        // inserted to make Paginierung the starting view
        this.modusAnsicht = "Metadaten";
    }
    return "metseditor";
}
Also used : ReadException(ugh.exceptions.ReadException) Metadata(ugh.dl.Metadata) TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) JDOMException(org.jdom2.JDOMException) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) PreferencesException(ugh.exceptions.PreferencesException) WriteException(ugh.exceptions.WriteException) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) IncompletePersonObjectException(ugh.exceptions.IncompletePersonObjectException) IOException(java.io.IOException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) ReadException(ugh.exceptions.ReadException) InvalidImagesException(de.sub.goobi.helper.exceptions.InvalidImagesException) DocStructHasNoTypeException(ugh.exceptions.DocStructHasNoTypeException) DocStruct(ugh.dl.DocStruct)

Example 2 with PreferencesException

use of ugh.exceptions.PreferencesException in project goobi-workflow by intranda.

the class Metadaten method XMLschreiben.

/**
 * Metadaten Schreiben
 *
 * @throws InterruptedException
 * @throws IOException ============================================================ == ==
 * @throws DAOException
 * @throws SwapException
 * @throws WriteException
 * @throws PreferencesException
 */
public String XMLschreiben() {
    XmlArtikelZaehlen zaehlen = new XmlArtikelZaehlen();
    this.myProzess.setSortHelperDocstructs(zaehlen.getNumberOfUghElements(this.logicalTopstruct, CountType.DOCSTRUCT));
    this.myProzess.setSortHelperMetadata(zaehlen.getNumberOfUghElements(this.logicalTopstruct, CountType.METADATA));
    try {
        this.myProzess.setSortHelperImages(StorageProvider.getInstance().getNumberOfFiles(Paths.get(this.myProzess.getImagesOrigDirectory(true))));
        ProcessManager.saveProcess(this.myProzess);
    } catch (DAOException e) {
        Helper.setFehlerMeldung("fehlerNichtSpeicherbar", e);
        log.error(e);
    } catch (Exception e) {
        Helper.setFehlerMeldung("error while counting current images", e);
        log.error(e);
    }
    /* xml-Datei speichern */
    // MetadatenDebuggen(gdzfile.getDigitalDocument().getLogicalDocStruct());
    /*
         * --------------------- vor dem Speichern alle ungenutzen Docstructs rauswerfen -------------------
         */
    this.metahelper.deleteAllUnusedElements(this.document.getLogicalDocStruct());
    updateRepresentativePage();
    // reading direction
    setRepresentativeMetadata();
    try {
        // if (!new MetadatenVerifizierungWithoutHibernate().validateIdentifier(gdzfile.getDigitalDocument().getLogicalDocStruct())) {
        // return false;
        // }
        this.myProzess.writeMetadataFile(this.gdzfile);
    } catch (Exception e) {
        Helper.setFehlerMeldung("Metafile is not writable.", e);
        log.error(e);
        return "Metadaten";
    }
    myProzess.removeTemporaryMetadataFiles();
    SperrungAufheben();
    return this.zurueck;
}
Also used : DAOException(de.sub.goobi.helper.exceptions.DAOException) XmlArtikelZaehlen(de.sub.goobi.helper.XmlArtikelZaehlen) TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) JDOMException(org.jdom2.JDOMException) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) PreferencesException(ugh.exceptions.PreferencesException) WriteException(ugh.exceptions.WriteException) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) IncompletePersonObjectException(ugh.exceptions.IncompletePersonObjectException) IOException(java.io.IOException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) ReadException(ugh.exceptions.ReadException) InvalidImagesException(de.sub.goobi.helper.exceptions.InvalidImagesException) DocStructHasNoTypeException(ugh.exceptions.DocStructHasNoTypeException)

Example 3 with PreferencesException

use of ugh.exceptions.PreferencesException in project goobi-workflow by intranda.

the class XmlArtikelZaehlen method getNumberOfUghElements.

/**
 * Anzahl der Strukturelemente ermitteln
 *
 * @param myProzess
 */
public int getNumberOfUghElements(Process myProzess, CountType inType) {
    int rueckgabe = 0;
    /* --------------------------------
         * Dokument einlesen
         * --------------------------------*/
    Fileformat gdzfile;
    try {
        gdzfile = myProzess.readMetadataFile();
    } catch (Exception e) {
        Helper.setFehlerMeldung("xml error", e.getMessage());
        return -1;
    }
    /* --------------------------------
         * DocStruct rukursiv durchlaufen
         * --------------------------------*/
    DigitalDocument mydocument = null;
    try {
        mydocument = gdzfile.getDigitalDocument();
        DocStruct logicalTopstruct = mydocument.getLogicalDocStruct();
        rueckgabe += getNumberOfUghElements(logicalTopstruct, inType);
    } catch (PreferencesException e1) {
        Helper.setFehlerMeldung("[" + myProzess.getId() + "] Can not get DigitalDocument: ", e1.getMessage());
        log.error(e1);
        rueckgabe = 0;
    }
    /* --------------------------------
         * die ermittelte Zahl im Prozess speichern
         * --------------------------------*/
    myProzess.setSortHelperArticles(Integer.valueOf(rueckgabe));
    try {
        ProcessManager.saveProcess(myProzess);
    } catch (DAOException e) {
        log.error(e);
    }
    return rueckgabe;
}
Also used : DAOException(de.sub.goobi.helper.exceptions.DAOException) Fileformat(ugh.dl.Fileformat) DigitalDocument(ugh.dl.DigitalDocument) PreferencesException(ugh.exceptions.PreferencesException) DAOException(de.sub.goobi.helper.exceptions.DAOException) PreferencesException(ugh.exceptions.PreferencesException) DocStruct(ugh.dl.DocStruct)

Example 4 with PreferencesException

use of ugh.exceptions.PreferencesException in project goobi-workflow by intranda.

the class ExportMets method collectMetadataToSave.

private ExportFileformat collectMetadataToSave(Process myProzess, Fileformat gdzfile, boolean writeLocalFilegroup, ConfigurationHelper config) throws IOException, InterruptedException, SwapException, DAOException, PreferencesException, TypeNotAllowedForParentException {
    ExportFileformat mm = MetadatenHelper.getExportFileformatByName(myProzess.getProjekt().getFileFormatDmsExport(), myProzess.getRegelsatz());
    mm.setWriteLocal(writeLocalFilegroup);
    mm.setCreateUUIDs(config.isExportCreateUUIDsAsFileIDs());
    String imageFolderPath = myProzess.getImagesTifDirectory(true);
    Path imageFolder = Paths.get(imageFolderPath);
    /*
         * before creating mets file, change relative path to absolute -
         */
    DigitalDocument dd = gdzfile.getDigitalDocument();
    MetadatenImagesHelper mih = new MetadatenImagesHelper(this.myPrefs, dd);
    if (dd.getFileSet() == null || dd.getFileSet().getAllFiles().isEmpty()) {
        Helper.setMeldung(myProzess.getTitel() + ": digital document does not contain images; adding them for mets file creation");
        mih.createPagination(myProzess, null);
        try {
            myProzess.writeMetadataFile(gdzfile);
        } catch (UGHException | IOException | InterruptedException | SwapException | DAOException e) {
            log.error(e);
        }
    } else {
        mih.checkImageNames(myProzess, imageFolder.getFileName().toString());
    }
    /*
         * get the topstruct element of the digital document depending on anchor property
         */
    DocStruct topElement = dd.getLogicalDocStruct();
    if (topElement.getType().isAnchor()) {
        if (topElement.getAllChildren() == null || topElement.getAllChildren().size() == 0) {
            throw new PreferencesException(myProzess.getTitel() + ": the topstruct element is marked as anchor, but does not have any children for physical docstrucs");
        } else {
            topElement = topElement.getAllChildren().get(0);
        }
    }
    if (config.isExportValidateImages()) {
        if (topElement.getAllToReferences("logical_physical") == null || topElement.getAllToReferences("logical_physical").size() == 0) {
            if (dd.getPhysicalDocStruct() != null && dd.getPhysicalDocStruct().getAllChildren() != null) {
                Helper.setMeldung(myProzess.getTitel() + ": topstruct element does not have any referenced images yet; temporarily adding them for mets file creation");
                for (DocStruct mySeitenDocStruct : dd.getPhysicalDocStruct().getAllChildren()) {
                    topElement.addReferenceTo(mySeitenDocStruct, "logical_physical");
                }
            } else {
                Helper.setFehlerMeldung(myProzess.getTitel() + ": could not find any referenced images, export aborted");
                dd = null;
                return null;
            }
        }
        for (ContentFile cf : dd.getFileSet().getAllFiles()) {
            String location = cf.getLocation();
            // use the file protocol.
            if (!location.contains("://")) {
                if (!location.matches("^[A-Z]:.*") && !location.matches("^\\/.*")) {
                    // is a relative path
                    Path f = Paths.get(imageFolder.toString(), location);
                    location = f.toString();
                }
                location = "file://" + location;
            }
            cf.setLocation(location);
        }
    }
    mm.setDigitalDocument(dd);
    // if configured, extract metadata from files and store them as techMd premis
    if (config.isExportCreateTechnicalMetadata()) {
        int counter = 1;
        for (DocStruct page : dd.getPhysicalDocStruct().getAllChildren()) {
            Path path = Paths.get(page.getImageName());
            if (!path.isAbsolute()) {
                path = Paths.get(imageFolder.toString(), page.getImageName());
            }
            Element techMd = createTechMd(path);
            if (techMd != null) {
                Md md = new Md(techMd);
                md.setType("techMD");
                md.setId(String.format("AMD_%04d", counter++));
                dd.addTechMd(md);
                page.setAdmId(md.getId());
            }
        }
    }
    Map<String, String> additionalMetadataMap = config.getExportWriteAdditionalMetadata();
    if (!additionalMetadataMap.isEmpty()) {
        String projectMetadataName = additionalMetadataMap.get("Project");
        String institutionMetadataName = additionalMetadataMap.get("Institution");
        Prefs prefs = myProzess.getRegelsatz().getPreferences();
        if (StringUtils.isNotBlank(projectMetadataName)) {
            MetadataType mdt = prefs.getMetadataTypeByName(projectMetadataName);
            if (mdt != null) {
                try {
                    ugh.dl.Metadata md = new ugh.dl.Metadata(mdt);
                    md.setValue(myProzess.getProjekt().getTitel());
                    topElement.addMetadata(md);
                } catch (MetadataTypeNotAllowedException e) {
                    log.warn("Configured metadata for project name is unknown or not allowed.");
                }
                if (topElement.getParent() != null) {
                    try {
                        ugh.dl.Metadata md = new ugh.dl.Metadata(mdt);
                        md.setValue(myProzess.getProjekt().getTitel());
                        topElement.getParent().addMetadata(md);
                    } catch (MetadataTypeNotAllowedException e) {
                        log.warn("Configured metadata for project name is unknown or not allowed.");
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(institutionMetadataName)) {
            MetadataType mdt = prefs.getMetadataTypeByName(institutionMetadataName);
            if (mdt != null) {
                try {
                    ugh.dl.Metadata md = new ugh.dl.Metadata(mdt);
                    md.setValue(myProzess.getProjekt().getInstitution().getLongName());
                    topElement.addMetadata(md);
                } catch (MetadataTypeNotAllowedException e) {
                    log.warn("Configured metadata for institution name is unknown or not allowed.");
                }
                if (topElement.getParent() != null) {
                    try {
                        ugh.dl.Metadata md = new ugh.dl.Metadata(mdt);
                        md.setValue(myProzess.getProjekt().getInstitution().getLongName());
                        topElement.getParent().addMetadata(md);
                    } catch (MetadataTypeNotAllowedException e) {
                        log.warn("Configured metadata for institution name is unknown or not allowed.");
                    }
                }
            }
        }
    }
    /*
         * -------------------------------- wenn Filegroups definiert wurden, werden diese jetzt in die Metsstruktur übernommen
         * --------------------------------
         */
    // Replace all pathes with the given VariableReplacer, also the file
    // group pathes!
    VariableReplacer vp = new VariableReplacer(mm.getDigitalDocument(), this.myPrefs, myProzess, null);
    List<ProjectFileGroup> myFilegroups = myProzess.getProjekt().getFilegroups();
    boolean useOriginalFiles = false;
    if (myFilegroups != null && myFilegroups.size() > 0) {
        for (ProjectFileGroup pfg : myFilegroups) {
            if (pfg.isUseOriginalFiles()) {
                useOriginalFiles = true;
            }
            // check if source files exists
            if (pfg.getFolder() != null && pfg.getFolder().length() > 0) {
                String foldername = myProzess.getMethodFromName(pfg.getFolder());
                if (foldername != null) {
                    Path folder = Paths.get(myProzess.getMethodFromName(pfg.getFolder()));
                    if (folder != null && StorageProvider.getInstance().isFileExists(folder) && !StorageProvider.getInstance().list(folder.toString()).isEmpty()) {
                        VirtualFileGroup v = createFilegroup(vp, pfg);
                        mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v);
                    }
                }
            } else {
                VirtualFileGroup v = createFilegroup(vp, pfg);
                mm.getDigitalDocument().getFileSet().addVirtualFileGroup(v);
            }
        }
    }
    if (useOriginalFiles) {
        // check if media folder contains images
        List<Path> filesInFolder = StorageProvider.getInstance().listFiles(myProzess.getImagesTifDirectory(false));
        if (!filesInFolder.isEmpty()) {
            // compare image names with files in mets file
            List<DocStruct> pages = dd.getPhysicalDocStruct().getAllChildren();
            if (pages != null && pages.size() > 0) {
                for (DocStruct page : pages) {
                    Path completeNameInMets = Paths.get(page.getImageName());
                    String filenameInMets = completeNameInMets.getFileName().toString();
                    int dotIndex = filenameInMets.lastIndexOf('.');
                    if (dotIndex != -1) {
                        filenameInMets = filenameInMets.substring(0, dotIndex);
                    }
                    for (Path imageNameInFolder : filesInFolder) {
                        String imageName = imageNameInFolder.getFileName().toString();
                        dotIndex = imageName.lastIndexOf('.');
                        if (dotIndex != -1) {
                            imageName = imageName.substring(0, dotIndex);
                        }
                        if (filenameInMets.toLowerCase().equals(imageName.toLowerCase())) {
                            // found matching filename
                            page.setImageName(imageNameInFolder.toString());
                            break;
                        }
                    }
                }
            // replace filename in mets file
            }
        }
    }
    // Replace rights and digiprov entries.
    mm.setRightsOwner(vp.replace(myProzess.getProjekt().getMetsRightsOwner()));
    mm.setRightsOwnerLogo(vp.replace(myProzess.getProjekt().getMetsRightsOwnerLogo()));
    mm.setRightsOwnerSiteURL(vp.replace(myProzess.getProjekt().getMetsRightsOwnerSite()));
    mm.setRightsOwnerContact(vp.replace(myProzess.getProjekt().getMetsRightsOwnerMail()));
    mm.setDigiprovPresentation(vp.replace(myProzess.getProjekt().getMetsDigiprovPresentation()));
    mm.setDigiprovReference(vp.replace(myProzess.getProjekt().getMetsDigiprovReference()));
    mm.setDigiprovPresentationAnchor(vp.replace(myProzess.getProjekt().getMetsDigiprovPresentationAnchor()));
    mm.setDigiprovReferenceAnchor(vp.replace(myProzess.getProjekt().getMetsDigiprovReferenceAnchor()));
    mm.setMetsRightsLicense(vp.replace(myProzess.getProjekt().getMetsRightsLicense()));
    mm.setMetsRightsSponsor(vp.replace(myProzess.getProjekt().getMetsRightsSponsor()));
    mm.setMetsRightsSponsorLogo(vp.replace(myProzess.getProjekt().getMetsRightsSponsorLogo()));
    mm.setMetsRightsSponsorSiteURL(vp.replace(myProzess.getProjekt().getMetsRightsSponsorSiteURL()));
    mm.setPurlUrl(vp.replace(myProzess.getProjekt().getMetsPurl()));
    mm.setContentIDs(vp.replace(myProzess.getProjekt().getMetsContentIDs()));
    String pointer = myProzess.getProjekt().getMetsPointerPath();
    pointer = vp.replace(pointer);
    mm.setMptrUrl(pointer);
    String anchor = myProzess.getProjekt().getMetsPointerPathAnchor();
    pointer = vp.replace(anchor);
    mm.setMptrAnchorUrl(pointer);
    mm.setGoobiID(String.valueOf(myProzess.getId()));
    mm.setIIIFUrl(vp.replace(myProzess.getProjekt().getMetsIIIFUrl()));
    mm.setSruUrl(vp.replace(myProzess.getProjekt().getMetsSruUrl()));
    // if (!ConfigMain.getParameter("ImagePrefix", "\\d{8}").equals("\\d{8}")) {
    List<String> images = new ArrayList<>();
    if (config.isExportValidateImages()) {
        try {
            images = new MetadatenImagesHelper(this.myPrefs, dd).getDataFiles(myProzess, imageFolderPath);
            int sizeOfPagination = dd.getPhysicalDocStruct().getAllChildren().size();
            if (images != null) {
                int sizeOfImages = images.size();
                if (sizeOfPagination == sizeOfImages) {
                    dd.overrideContentFiles(images);
                } else {
                    String[] param = { String.valueOf(sizeOfPagination), String.valueOf(sizeOfImages) };
                    Helper.setFehlerMeldung(Helper.getTranslation("imagePaginationError", param));
                    return null;
                }
            }
        } catch (IndexOutOfBoundsException e) {
            log.error(e);
            return null;
        } catch (InvalidImagesException e) {
            log.error(e);
            return null;
        }
    } else {
        // create pagination out of virtual file names
        dd.addAllContentFiles();
    }
    return mm;
}
Also used : ContentFile(ugh.dl.ContentFile) ProjectFileGroup(org.goobi.beans.ProjectFileGroup) SwapException(de.sub.goobi.helper.exceptions.SwapException) Element(org.w3c.dom.Element) Metadata(com.drew.metadata.Metadata) ArrayList(java.util.ArrayList) VariableReplacer(de.sub.goobi.helper.VariableReplacer) Prefs(ugh.dl.Prefs) DAOException(de.sub.goobi.helper.exceptions.DAOException) MetadatenImagesHelper(de.sub.goobi.metadaten.MetadatenImagesHelper) VirtualFileGroup(ugh.dl.VirtualFileGroup) DocStruct(ugh.dl.DocStruct) Path(java.nio.file.Path) MetadataType(ugh.dl.MetadataType) UGHException(ugh.exceptions.UGHException) IOException(java.io.IOException) DigitalDocument(ugh.dl.DigitalDocument) InvalidImagesException(de.sub.goobi.helper.exceptions.InvalidImagesException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) Md(ugh.dl.Md) PreferencesException(ugh.exceptions.PreferencesException) ExportFileformat(ugh.dl.ExportFileformat)

Example 5 with PreferencesException

use of ugh.exceptions.PreferencesException in project goobi-workflow by intranda.

the class ExportPdf method startExport.

@Override
public boolean startExport(Process myProzess, String inZielVerzeichnis) throws IOException, InterruptedException, PreferencesException, WriteException, DocStructHasNoTypeException, MetadataTypeNotAllowedException, ExportFileException, UghHelperException, ReadException, SwapException, DAOException, TypeNotAllowedForParentException {
    /*
         * -------------------------------- Read Document --------------------------------
         */
    Fileformat gdzfile = myProzess.readMetadataFile();
    String zielVerzeichnis = prepareUserDirectory(inZielVerzeichnis);
    this.myPrefs = myProzess.getRegelsatz().getPreferences();
    /*
         * -------------------------------- first of all write mets-file in images-Folder of process --------------------------------
         */
    Path metsTempFile = StorageProvider.getInstance().createTemporaryFile(myProzess.getTitel(), ".xml");
    writeMetsFile(myProzess, metsTempFile.toString(), gdzfile, true);
    Helper.setMeldung(null, myProzess.getTitel() + ": ", "mets file created");
    Helper.setMeldung(null, myProzess.getTitel() + ": ", "start pdf generation now");
    log.debug("METS file created: " + metsTempFile);
    FacesContext context = FacesContextHelper.getCurrentFacesContext();
    HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
    String fullpath = req.getRequestURL().toString();
    String servletpath = context.getExternalContext().getRequestServletPath();
    String myBasisUrl = fullpath.substring(0, fullpath.indexOf(servletpath));
    Path imagesPath = Paths.get(myProzess.getImagesTifDirectory(true));
    if (!StorageProvider.getInstance().isFileExists(imagesPath) || StorageProvider.getInstance().list(imagesPath.toString(), NIOFileUtils.imageNameFilter).isEmpty()) {
        imagesPath = Paths.get(myProzess.getImagesOrigDirectory(true));
    }
    Path pdfPath = Paths.get(myProzess.getOcrPdfDirectory());
    Path altoPath = Paths.get(myProzess.getOcrAltoDirectory());
    if (!ConfigurationHelper.getInstance().isPdfAsDownload()) {
        /*
             * -------------------------------- use contentserver api for creation of pdf-file --------------------------------
             */
        CreatePdfFromServletThread pdf = new CreatePdfFromServletThread();
        pdf.setMetsURL(metsTempFile.toUri().toURL());
        pdf.setTargetFolder(Paths.get(zielVerzeichnis));
        pdf.setInternalServletPath(myBasisUrl);
        pdf.setImagePath(imagesPath);
        pdf.setPdfPath(pdfPath);
        pdf.setAltoPath(altoPath);
        log.debug("Taget directory: " + zielVerzeichnis);
        log.debug("Using ContentServer2 base URL: " + myBasisUrl);
        pdf.initialize(myProzess);
        pdf.start();
    } else {
        try {
            /*
                 * -------------------------------- define path for mets and pdfs --------------------------------
                 */
            URL goobiContentServerUrl = null;
            String contentServerUrl = ConfigurationHelper.getInstance().getGoobiContentServerUrl();
            String imageSource = "&imageSource=" + imagesPath.toUri();
            String pdfSource = "&pdfSource=" + pdfPath.toUri();
            String altoSource = "&altoSource=" + altoPath.toUri();
            if (StorageProvider.getInstance().isFileExists(metsTempFile)) {
                /* if no contentserverurl defined use internal goobiContentServerServlet */
                if (contentServerUrl == null || contentServerUrl.length() == 0) {
                    contentServerUrl = myBasisUrl + "/gcs/gcs?action=pdf&metsFile=";
                }
                goobiContentServerUrl = new URL(contentServerUrl + metsTempFile.toUri().toURL() + imageSource + pdfSource + altoSource + "&targetFileName=" + myProzess.getTitel() + ".pdf");
            /*
                     * -------------------------------- mets data does not exist or is invalid --------------------------------
                     */
            } else {
                if (contentServerUrl == null || contentServerUrl.length() == 0) {
                    contentServerUrl = myBasisUrl + "/cs/cs?action=pdf&images=";
                }
                String url = "";
                List<Path> meta = StorageProvider.getInstance().listFiles(myProzess.getImagesTifDirectory(true), NIOFileUtils.imageNameFilter);
                ArrayList<String> filenames = new ArrayList<>();
                for (Path data : meta) {
                    String file = "";
                    file += data.toUri().toURL();
                    filenames.add(file);
                }
                Collections.sort(filenames, new MetadatenHelper(null, null));
                for (String f : filenames) {
                    url = url + f + "$";
                }
                String imageString = url.substring(0, url.length() - 1);
                String targetFileName = "&targetFileName=" + myProzess.getTitel() + ".pdf";
                goobiContentServerUrl = new URL(contentServerUrl + imageString + imageSource + pdfSource + altoSource + targetFileName);
            }
            if (!context.getResponseComplete()) {
                log.debug("Redirecting pdf request to " + goobiContentServerUrl.toString());
                HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
                String fileName = myProzess.getTitel() + ".pdf";
                ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
                String contentType = servletContext.getMimeType(fileName);
                response.setContentType(contentType);
                response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                response.sendRedirect(goobiContentServerUrl.toString());
                context.responseComplete();
            }
        // if (Files.exists(metsTempFile)) {
        // Path tempMets = Paths.get(metsTempFile.toUri().toURL().toString());
        // Files.delete(metsTempFile);
        // }
        } catch (Exception e) {
            /*
                 * -------------------------------- report Error to User as Error-Log --------------------------------
                 */
            Writer output = null;
            String text = "error while pdf creation: " + e.getMessage();
            Path file = Paths.get(zielVerzeichnis, myProzess.getTitel() + ".PDF-ERROR.log");
            try {
                log.error(e);
                output = new BufferedWriter(new FileWriter(file.toFile()));
                output.write(text);
                output.close();
            } catch (IOException e1) {
            }
            return false;
        }
    }
    return true;
}
Also used : Path(java.nio.file.Path) FacesContext(javax.faces.context.FacesContext) CreatePdfFromServletThread(de.sub.goobi.helper.tasks.CreatePdfFromServletThread) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) Fileformat(ugh.dl.Fileformat) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) URL(java.net.URL) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) ExportFileException(de.sub.goobi.helper.exceptions.ExportFileException) UghHelperException(de.sub.goobi.helper.exceptions.UghHelperException) IOException(java.io.IOException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) PreferencesException(ugh.exceptions.PreferencesException) ReadException(ugh.exceptions.ReadException) DocStructHasNoTypeException(ugh.exceptions.DocStructHasNoTypeException) WriteException(ugh.exceptions.WriteException) BufferedWriter(java.io.BufferedWriter) HttpServletRequest(javax.servlet.http.HttpServletRequest) MetadatenHelper(de.sub.goobi.metadaten.MetadatenHelper) ServletContext(javax.servlet.ServletContext) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer)

Aggregations

PreferencesException (ugh.exceptions.PreferencesException)19 DAOException (de.sub.goobi.helper.exceptions.DAOException)14 SwapException (de.sub.goobi.helper.exceptions.SwapException)13 IOException (java.io.IOException)13 DocStruct (ugh.dl.DocStruct)11 MetadataTypeNotAllowedException (ugh.exceptions.MetadataTypeNotAllowedException)11 WriteException (ugh.exceptions.WriteException)11 DocStructHasNoTypeException (ugh.exceptions.DocStructHasNoTypeException)10 ReadException (ugh.exceptions.ReadException)10 TypeNotAllowedForParentException (ugh.exceptions.TypeNotAllowedForParentException)9 UghHelperException (de.sub.goobi.helper.exceptions.UghHelperException)8 Fileformat (ugh.dl.Fileformat)7 Path (java.nio.file.Path)6 InvalidImagesException (de.sub.goobi.helper.exceptions.InvalidImagesException)5 JDOMException (org.jdom2.JDOMException)5 DigitalDocument (ugh.dl.DigitalDocument)5 ExportFileException (de.sub.goobi.helper.exceptions.ExportFileException)4 ArrayList (java.util.ArrayList)4 ExportFileformat (ugh.dl.ExportFileformat)4 Metadata (ugh.dl.Metadata)4