Search in sources :

Example 1 with UGHException

use of ugh.exceptions.UGHException 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 2 with UGHException

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

the class ProzesskopieForm method NeuenProzessAnlegen.

/**
 * Anlegen des Processes und Speichern der Metadaten ================================================================
 *
 * @throws DAOException
 * @throws SwapException
 * @throws WriteException
 */
public String NeuenProzessAnlegen() throws ReadException, IOException, InterruptedException, PreferencesException, SwapException, DAOException, WriteException {
    if (this.prozessKopie.getTitel() == null || this.prozessKopie.getTitel().equals("")) {
        CalcProzesstitel();
    }
    if (!isContentValid()) {
        return this.naviFirstPage;
    }
    EigenschaftenHinzufuegen();
    LoginBean loginForm = Helper.getLoginBean();
    for (Step step : this.prozessKopie.getSchritteList()) {
        /*
             * -------------------------------- only if its done, set edit start and end date --------------------------------
             */
        if (step.getBearbeitungsstatusEnum() == StepStatus.DONE) {
            step.setBearbeitungszeitpunkt(this.prozessKopie.getErstellungsdatum());
            step.setEditTypeEnum(StepEditType.AUTOMATIC);
            if (loginForm != null) {
                step.setBearbeitungsbenutzer(loginForm.getMyBenutzer());
            }
            step.setBearbeitungsbeginn(this.prozessKopie.getErstellungsdatum());
            // this concerns steps, which are set as done right on creation
            // bearbeitungsbeginn is set to creation timestamp of process
            // because the creation of it is basically begin of work
            Date myDate = new Date();
            step.setBearbeitungszeitpunkt(myDate);
            step.setBearbeitungsende(myDate);
        }
    }
    this.prozessKopie.setSortHelperImages(this.guessedImages);
    ProcessManager.saveProcess(this.prozessKopie);
    if (currentCatalogue != null && currentCatalogue.getOpacPlugin() != null && currentCatalogue.getOpacPlugin() instanceof IOpacPluginVersion2) {
        IOpacPluginVersion2 opacPluginV2 = (IOpacPluginVersion2) currentCatalogue.getOpacPlugin();
        // check if the plugin created files
        if (opacPluginV2.getRecordPathList() != null) {
            for (Path record : opacPluginV2.getRecordPathList()) {
                // if this is the case, move the files to the import/ folder
                Path destination = Paths.get(prozessKopie.getImportDirectory(), record.getFileName().toString());
                StorageProvider.getInstance().createDirectories(destination.getParent());
                StorageProvider.getInstance().move(record, destination);
            }
        }
        // check if the plugin provides the data as string
        if (opacPluginV2.getRawDataAsString() != null) {
            // if this is the case, store it in a file in import/
            for (Entry<String, String> entry : opacPluginV2.getRawDataAsString().entrySet()) {
                Path destination = Paths.get(prozessKopie.getImportDirectory(), entry.getKey().replaceAll("\\W", "_"));
                StorageProvider.getInstance().createDirectories(destination.getParent());
                Files.write(destination, entry.getValue().getBytes());
            }
        }
    }
    if (addToWikiField != null && !addToWikiField.equals("")) {
        User user = loginForm.getMyBenutzer();
        LogEntry logEntry = new LogEntry();
        logEntry.setContent(addToWikiField);
        logEntry.setCreationDate(new Date());
        logEntry.setProcessId(prozessKopie.getId());
        logEntry.setType(LogType.INFO);
        logEntry.setUserName(user.getNachVorname());
        ProcessManager.saveLogEntry(logEntry);
        prozessKopie.getProcessLog().add(logEntry);
    }
    /*
         * wenn noch keine RDF-Datei vorhanden ist (weil keine Opac-Abfrage stattfand, dann jetzt eine anlegen
         */
    if (this.myRdf == null) {
        try {
            createNewFileformat();
        } catch (TypeNotAllowedForParentException | TypeNotAllowedAsChildException e) {
            Helper.setFehlerMeldung("ProcessCreationError_mets_save_error");
            Helper.setFehlerMeldung(e);
            ProcessManager.deleteProcess(prozessKopie);
            // this ensures that the process will be saved later, if corrected. If
            // the id is not null, then it is assumed that the process is already saved.
            prozessKopie.setId(null);
            return "";
        }
    }
    /*--------------------------------
         * wenn eine RDF-Konfiguration
         * vorhanden ist (z.B. aus dem Opac-Import, oder frisch angelegt), dann
         * diese ergänzen
         * --------------------------------*/
    if (this.myRdf != null) {
        for (AdditionalField field : this.additionalFields) {
            if (field.isUghbinding() && field.getShowDependingOnDoctype(getDocType())) {
                /* welches Docstruct */
                DocStruct myTempStruct = this.myRdf.getDigitalDocument().getLogicalDocStruct();
                DocStruct myTempChild = null;
                if (field.getDocstruct().equals("firstchild")) {
                    try {
                        myTempStruct = this.myRdf.getDigitalDocument().getLogicalDocStruct().getAllChildren().get(0);
                    } catch (RuntimeException e) {
                    /*
                             * das Firstchild unterhalb des Topstructs konnte nicht ermittelt werden
                             */
                    }
                }
                /*
                     * falls topstruct und firstchild das Metadatum bekommen sollen
                     */
                if (!field.getDocstruct().equals("firstchild") && field.getDocstruct().contains("firstchild")) {
                    try {
                        myTempChild = this.myRdf.getDigitalDocument().getLogicalDocStruct().getAllChildren().get(0);
                    } catch (RuntimeException e) {
                    }
                }
                if (field.getDocstruct().equals("boundbook")) {
                    myTempStruct = this.myRdf.getDigitalDocument().getPhysicalDocStruct();
                }
                /* welches Metadatum */
                try {
                    /*
                         * bis auf die Autoren alle additionals in die Metadaten übernehmen
                         */
                    if (!field.getMetadata().equals("ListOfCreators")) {
                        MetadataType mdt = this.ughHelper.getMetadataType(this.prozessKopie.getRegelsatz().getPreferences(), field.getMetadata());
                        Metadata md = this.ughHelper.getMetadata(myTempStruct, mdt);
                        if (md != null) {
                            md.setValue(field.getWert());
                        } else if (// if the md could not be found, warn!
                        this.ughHelper.lastErrorMessage != null && field.getWert() != null && !field.getWert().isEmpty()) {
                            Helper.setFehlerMeldung(this.ughHelper.lastErrorMessage);
                            String strError = mdt.getName() + " : " + field.getWert();
                            Helper.setFehlerMeldung(strError);
                        }
                        /*
                             * wenn dem Topstruct und dem Firstchild der Wert gegeben werden soll
                             */
                        if (myTempChild != null) {
                            md = this.ughHelper.getMetadata(myTempChild, mdt);
                            if (md != null) {
                                md.setValue(field.getWert());
                            }
                        }
                    }
                } catch (Exception e) {
                    Helper.setFehlerMeldung(e);
                }
            }
        // end if ughbinding
        }
        // end for
        /*
             * -------------------------------- Collectionen hinzufügen --------------------------------
             */
        DocStruct colStruct = this.myRdf.getDigitalDocument().getLogicalDocStruct();
        try {
            addCollections(colStruct);
            /* falls ein erstes Kind vorhanden ist, sind die Collectionen dafür */
            colStruct = colStruct.getAllChildren().get(0);
            addCollections(colStruct);
        } catch (RuntimeException e) {
        /*
                 * das Firstchild unterhalb des Topstructs konnte nicht ermittelt werden
                 */
        }
        /*
             * -------------------------------- Imagepfad hinzufügen (evtl. vorhandene zunächst löschen) --------------------------------
             */
        try {
            MetadataType mdt = this.ughHelper.getMetadataType(this.prozessKopie, "pathimagefiles");
            List<? extends Metadata> alleImagepfade = this.myRdf.getDigitalDocument().getPhysicalDocStruct().getAllMetadataByType(mdt);
            if (alleImagepfade != null && alleImagepfade.size() > 0) {
                for (Metadata md : alleImagepfade) {
                    this.myRdf.getDigitalDocument().getPhysicalDocStruct().getAllMetadata().remove(md);
                }
            }
            Metadata newmd = new Metadata(mdt);
            if (SystemUtils.IS_OS_WINDOWS) {
                newmd.setValue("file:/" + this.prozessKopie.getImagesDirectory() + this.prozessKopie.getTitel().trim() + DIRECTORY_SUFFIX);
            } else {
                newmd.setValue("file://" + this.prozessKopie.getImagesDirectory() + this.prozessKopie.getTitel().trim() + DIRECTORY_SUFFIX);
            }
            this.myRdf.getDigitalDocument().getPhysicalDocStruct().addMetadata(newmd);
            /* Rdf-File schreiben */
            this.prozessKopie.writeMetadataFile(this.myRdf);
            try {
                this.prozessKopie.readMetadataFile();
            } catch (IOException e) {
                Helper.setFehlerMeldung("ProcessCreationError_mets_save_error");
                ProcessManager.deleteProcess(prozessKopie);
                // this ensures that the process will be saved later, if corrected. If
                // the id is not null, then it is assumed that the process is already saved.
                prozessKopie.setId(null);
                return "";
            }
            /*
                 * -------------------------------- soll der Process als Vorlage verwendet werden? --------------------------------
                 */
            if (this.useTemplates && this.prozessKopie.isInAuswahllisteAnzeigen()) {
                this.prozessKopie.writeMetadataAsTemplateFile(this.myRdf);
            }
        } catch (UghHelperException | UGHException e) {
            Helper.setFehlerMeldung("ProcessCreationError_mets_save_error");
            Helper.setFehlerMeldung(e.getMessage());
            log.error("creation of new process throws an error: ", e);
            ProcessManager.deleteProcess(prozessKopie);
            // this ensures that the process will be saved later, if corrected. If
            // the id is not null, then it is assumed that the process is already saved.
            prozessKopie.setId(null);
            return "";
        }
    }
    // Adding process to history
    if (!HistoryAnalyserJob.updateHistoryForProzess(this.prozessKopie)) {
        Helper.setFehlerMeldung("historyNotUpdated");
        return "";
    } else {
        ProcessManager.saveProcess(this.prozessKopie);
    }
    // read all uploaded files, copy them to the right destination, create log entries
    if (!uploadedFiles.isEmpty()) {
        for (UploadImage image : uploadedFiles) {
            if (!image.isDeleted()) {
                Path folder = null;
                if ("intern".equals(image.getFoldername())) {
                    folder = Paths.get(prozessKopie.getProcessDataDirectory(), ConfigurationHelper.getInstance().getFolderForInternalProcesslogFiles());
                } else if ("export".equals(image.getFoldername())) {
                    folder = Paths.get(prozessKopie.getExportDirectory());
                } else {
                    folder = Paths.get(prozessKopie.getConfiguredImageFolder(image.getFoldername()));
                }
                if (!StorageProvider.getInstance().isFileExists(folder)) {
                    StorageProvider.getInstance().createDirectories(folder);
                }
                Path source = image.getImagePath();
                Path destination = Paths.get(folder.toString(), source.getFileName().toString());
                StorageProvider.getInstance().copyFile(source, destination);
                if ("intern".equals(image.getFoldername()) || "export".equals(image.getFoldername())) {
                    LogEntry entry = LogEntry.build(prozessKopie.getId()).withCreationDate(new Date()).withContent(image.getDescriptionText()).withType(LogType.FILE).withUsername(Helper.getCurrentUser().getNachVorname());
                    entry.setSecondContent(folder.toString());
                    entry.setThirdContent(destination.toString());
                    ProcessManager.saveLogEntry(entry);
                }
            }
        }
        // finally clean up
        for (UploadImage image : uploadedFiles) {
            try {
                StorageProvider.getInstance().deleteFile(image.getImagePath());
            } catch (Exception e) {
            // do nothing, as this happens if the same file gets used in multiple target folders
            }
        }
    }
    List<Step> steps = StepManager.getStepsForProcess(prozessKopie.getId());
    for (Step s : steps) {
        if (s.getBearbeitungsstatusEnum().equals(StepStatus.OPEN) && s.isTypAutomatisch()) {
            ScriptThreadWithoutHibernate myThread = new ScriptThreadWithoutHibernate(s);
            myThread.startOrPutToQueue();
        }
    }
    prozessKopie = ProcessManager.getProcessById(prozessKopie.getId());
    return "process_new3";
}
Also used : TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) User(org.goobi.beans.User) Metadata(ugh.dl.Metadata) Step(org.goobi.beans.Step) UghHelperException(de.sub.goobi.helper.exceptions.UghHelperException) IOpacPluginVersion2(org.goobi.production.plugin.interfaces.IOpacPluginVersion2) LogEntry(org.goobi.beans.LogEntry) DocStruct(ugh.dl.DocStruct) Path(java.nio.file.Path) TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) ScriptThreadWithoutHibernate(de.sub.goobi.helper.ScriptThreadWithoutHibernate) MetadataType(ugh.dl.MetadataType) UGHException(ugh.exceptions.UGHException) IOException(java.io.IOException) Date(java.util.Date) NamingException(javax.naming.NamingException) TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) JDOMException(org.jdom2.JDOMException) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) UghHelperException(de.sub.goobi.helper.exceptions.UghHelperException) PreferencesException(ugh.exceptions.PreferencesException) UGHException(ugh.exceptions.UGHException) WriteException(ugh.exceptions.WriteException) SQLException(java.sql.SQLException) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) IOException(java.io.IOException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) ReadException(ugh.exceptions.ReadException) DocStructHasNoTypeException(ugh.exceptions.DocStructHasNoTypeException) LoginBean(org.goobi.managedbeans.LoginBean)

Example 3 with UGHException

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

the class HelperSchritte method executeDmsExport.

public boolean executeDmsExport(Step step, boolean automatic) {
    if (automatic && step.getProzess().isPauseAutomaticExecution()) {
        // reOpenStep(step);
        return false;
    }
    IExportPlugin dms = null;
    if (StringUtils.isNotBlank(step.getStepPlugin())) {
        try {
            dms = (IExportPlugin) PluginLoader.getPluginByTitle(PluginType.Export, step.getStepPlugin());
        } catch (Exception e) {
            log.error("Can't load export plugin, use default export for process with ID " + step.getProcessId(), e);
            dms = new ExportDms(ConfigurationHelper.getInstance().isAutomaticExportWithImages());
        // dms = new AutomaticDmsExport(ConfigurationHelper.isAutomaticExportWithImages());
        }
    }
    if (dms == null) {
        dms = new ExportDms(ConfigurationHelper.getInstance().isAutomaticExportWithImages());
    // dms = new AutomaticDmsExport(ConfigurationHelper.getInstance().isAutomaticExportWithImages());
    }
    if (!ConfigurationHelper.getInstance().isAutomaticExportWithOcr()) {
        dms.setExportFulltext(false);
    }
    // ProcessObject po = ProcessManager.getProcessObjectForId(step.getProcessId());
    try {
        boolean validate = dms.startExport(step.getProzess());
        if (validate) {
            Helper.addMessageToProcessLog(step.getProcessId(), LogType.DEBUG, "The export for process with ID '" + step.getProcessId() + "' was done successfully.");
            CloseStepObjectAutomatic(step);
        } else {
            Helper.addMessageToProcessLog(step.getProcessId(), LogType.ERROR, "The export for process with ID '" + step.getProcessId() + "' was cancelled because of validation errors: " + dms.getProblems().toString());
            errorStep(step);
        }
        return validate;
    } catch (DAOException | UGHException | SwapException | IOException | InterruptedException | DocStructHasNoTypeException | UghHelperException | ExportFileException e) {
        log.error("Exception occurred while trying to export process with ID " + step.getProcessId(), e);
        Helper.addMessageToProcessLog(step.getProcessId(), LogType.ERROR, "An exception occurred during the export for process with ID " + step.getProcessId() + ": " + e.getMessage());
        errorStep(step);
        return false;
    }
}
Also used : ExportFileException(de.sub.goobi.helper.exceptions.ExportFileException) SwapException(de.sub.goobi.helper.exceptions.SwapException) ExportDms(de.sub.goobi.export.dms.ExportDms) UGHException(ugh.exceptions.UGHException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) JDOMException(org.jdom2.JDOMException) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) UghHelperException(de.sub.goobi.helper.exceptions.UghHelperException) KeyManagementException(java.security.KeyManagementException) PreferencesException(ugh.exceptions.PreferencesException) UGHException(ugh.exceptions.UGHException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) WriteException(ugh.exceptions.WriteException) ExportFileException(de.sub.goobi.helper.exceptions.ExportFileException) IOException(java.io.IOException) ReadException(ugh.exceptions.ReadException) DocStructHasNoTypeException(ugh.exceptions.DocStructHasNoTypeException) DAOException(de.sub.goobi.helper.exceptions.DAOException) IExportPlugin(org.goobi.production.plugin.interfaces.IExportPlugin) UghHelperException(de.sub.goobi.helper.exceptions.UghHelperException) DocStructHasNoTypeException(ugh.exceptions.DocStructHasNoTypeException)

Example 4 with UGHException

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

the class Process method writeMetadataFile.

public synchronized void writeMetadataFile(Fileformat gdzfile) throws IOException, InterruptedException, SwapException, DAOException, WriteException, PreferencesException {
    String path = this.getProcessDataDirectory();
    int maximumNumberOfBackups = ConfigurationHelper.getInstance().getNumberOfMetaBackups();
    // Backup meta.xml
    String metaFileName = "meta.xml";
    Path metaFile = Paths.get(path + metaFileName);
    String backupMetaFileName = Process.createBackup(path, metaFileName, maximumNumberOfBackups);
    Path backupMetaFile = Paths.get(path + backupMetaFileName);
    // Backup meta_anchor.xml
    String metaAnchorFileName = "meta_anchor.xml";
    Path metaAnchorFile = Paths.get(path + metaAnchorFileName);
    String backupMetaAnchorFileName = Process.createBackup(path, metaAnchorFileName, maximumNumberOfBackups);
    Path backupMetaAnchorFile = Paths.get(path + backupMetaAnchorFileName);
    Fileformat ff = MetadatenHelper.getFileformatByName(getProjekt().getFileFormatInternal(), this.regelsatz);
    synchronized (xmlWriteLock) {
        ff.setDigitalDocument(gdzfile.getDigitalDocument());
        try {
            ff.write(path + metaFileName);
        } catch (UGHException ughException) {
            // Restore meta.xml
            if ((!Files.exists(metaFile) || Files.size(metaFile) == 0) && Files.exists(backupMetaFile)) {
                Files.copy(backupMetaFile, metaFile, StandardCopyOption.REPLACE_EXISTING);
            }
            // Restore meta_anchor.xml
            if ((!Files.exists(metaAnchorFile) || Files.size(metaAnchorFile) == 0) && Files.exists(backupMetaAnchorFile)) {
                Files.copy(backupMetaAnchorFile, metaAnchorFile, StandardCopyOption.REPLACE_EXISTING);
            }
            throw ughException;
        }
    }
    Map<String, List<String>> metadata = MetadatenHelper.getMetadataOfFileformat(gdzfile, false);
    MetadataManager.updateMetadata(id, metadata);
    Map<String, List<String>> jsonMetadata = MetadatenHelper.getMetadataOfFileformat(gdzfile, true);
    MetadataManager.updateJSONMetadata(id, jsonMetadata);
}
Also used : Path(java.nio.file.Path) Fileformat(ugh.dl.Fileformat) UGHException(ugh.exceptions.UGHException) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList)

Example 5 with UGHException

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

the class Process method changeProcessTitle.

/**
 * Change the process title and rename folders, property values ezc
 */
public boolean changeProcessTitle(String newTitle) {
    /* Prozesseigenschaften */
    if (getEigenschaftenList() != null && !getEigenschaftenList().isEmpty()) {
        for (Processproperty pe : this.getEigenschaftenList()) {
            if (pe != null && pe.getWert() != null) {
                if (pe.getWert().contains(this.getTitel())) {
                    pe.setWert(pe.getWert().replaceAll(this.getTitel(), newTitle));
                }
            }
        }
    }
    /* Scanvorlageneigenschaften */
    if (getVorlagenList() != null && !getVorlagenList().isEmpty()) {
        for (Template vl : this.getVorlagenList()) {
            for (Templateproperty ve : vl.getEigenschaftenList()) {
                if (ve.getWert().contains(this.getTitel())) {
                    ve.setWert(ve.getWert().replaceAll(this.getTitel(), newTitle));
                }
            }
        }
    }
    /* Werkstückeigenschaften */
    if (getWerkstueckeList() != null && !getWerkstueckeList().isEmpty()) {
        for (Masterpiece w : this.getWerkstueckeList()) {
            for (Masterpieceproperty we : w.getEigenschaftenList()) {
                if (we.getWert().contains(this.getTitel())) {
                    we.setWert(we.getWert().replaceAll(this.getTitel(), newTitle));
                }
            }
        }
    }
    try {
        {
            // renaming image directories
            String imageDirectory = getImagesDirectory();
            Path dir = Paths.get(imageDirectory);
            if (StorageProvider.getInstance().isFileExists(dir) && StorageProvider.getInstance().isDirectory(dir)) {
                List<Path> subdirs = StorageProvider.getInstance().listFiles(imageDirectory);
                for (Path imagedir : subdirs) {
                    if (StorageProvider.getInstance().isDirectory(imagedir) || StorageProvider.getInstance().isSymbolicLink(imagedir)) {
                        StorageProvider.getInstance().move(imagedir, Paths.get(imagedir.toString().replace(getTitel(), newTitle)));
                    }
                }
            }
        }
        {
            // renaming ocr directories
            String ocrDirectory = getOcrDirectory();
            Path dir = Paths.get(ocrDirectory);
            if (StorageProvider.getInstance().isFileExists(dir) && StorageProvider.getInstance().isDirectory(dir)) {
                List<Path> subdirs = StorageProvider.getInstance().listFiles(ocrDirectory);
                for (Path imagedir : subdirs) {
                    if (StorageProvider.getInstance().isDirectory(imagedir) || StorageProvider.getInstance().isSymbolicLink(imagedir)) {
                        StorageProvider.getInstance().move(imagedir, Paths.get(imagedir.toString().replace(getTitel(), newTitle)));
                    }
                }
            }
        }
    } catch (Exception e) {
        log.trace("could not rename folder", e);
    }
    if (!this.isIstTemplate()) {
        /* Tiffwriter-Datei löschen */
        GoobiScript gs = new GoobiScript();
        List<Integer> pro = new ArrayList<>();
        pro.add(this.getId());
        gs.deleteTiffHeaderFile(pro);
        // update paths in metadata file
        try {
            Fileformat fileFormat = readMetadataFile();
            UghHelper ughhelp = new UghHelper();
            MetadataType mdt = ughhelp.getMetadataType(this, "pathimagefiles");
            DocStruct physical = fileFormat.getDigitalDocument().getPhysicalDocStruct();
            List<? extends ugh.dl.Metadata> alleImagepfade = physical.getAllMetadataByType(mdt);
            if (alleImagepfade.size() > 0) {
                for (Metadata md : alleImagepfade) {
                    fileFormat.getDigitalDocument().getPhysicalDocStruct().getAllMetadata().remove(md);
                }
            }
            Metadata newmd = new Metadata(mdt);
            String newFolder = getImagesTifDirectory(false).replace(getTitel(), newTitle);
            if (SystemUtils.IS_OS_WINDOWS) {
                newmd.setValue("file:/" + newFolder);
            } else {
                newmd.setValue("file://" + newFolder);
            }
            fileFormat.getDigitalDocument().getPhysicalDocStruct().addMetadata(newmd);
            if (physical.getAllChildren() != null) {
                for (DocStruct page : physical.getAllChildren()) {
                    List<ContentFile> contentFileList = page.getAllContentFiles();
                    if (contentFileList != null) {
                        for (ContentFile cf : contentFileList) {
                            cf.setLocation(cf.getLocation().replace(getTitel(), newTitle));
                        }
                    }
                }
            }
            writeMetadataFile(fileFormat);
        } catch (IOException | InterruptedException | SwapException | DAOException | UghHelperException | UGHException e) {
            log.info("Could not rename paths in metadata file", e);
        }
    }
    /* Vorgangstitel */
    this.setTitel(newTitle);
    return true;
}
Also used : GoobiScript(de.sub.goobi.helper.GoobiScript) ContentFile(ugh.dl.ContentFile) SwapException(de.sub.goobi.helper.exceptions.SwapException) ArrayList(java.util.ArrayList) XsltPreparatorMetadata(io.goobi.workflow.xslt.XsltPreparatorMetadata) Metadata(ugh.dl.Metadata) Fileformat(ugh.dl.Fileformat) DAOException(de.sub.goobi.helper.exceptions.DAOException) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) UghHelperException(de.sub.goobi.helper.exceptions.UghHelperException) DocStruct(ugh.dl.DocStruct) Path(java.nio.file.Path) MetadataType(ugh.dl.MetadataType) UGHException(ugh.exceptions.UGHException) IOException(java.io.IOException) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) UghHelperException(de.sub.goobi.helper.exceptions.UghHelperException) PreferencesException(ugh.exceptions.PreferencesException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UGHException(ugh.exceptions.UGHException) WriteException(ugh.exceptions.WriteException) IOException(java.io.IOException) ReadException(ugh.exceptions.ReadException) UghHelper(de.sub.goobi.helper.UghHelper)

Aggregations

UGHException (ugh.exceptions.UGHException)6 DAOException (de.sub.goobi.helper.exceptions.DAOException)5 SwapException (de.sub.goobi.helper.exceptions.SwapException)5 IOException (java.io.IOException)5 Path (java.nio.file.Path)5 PreferencesException (ugh.exceptions.PreferencesException)4 UghHelperException (de.sub.goobi.helper.exceptions.UghHelperException)3 ArrayList (java.util.ArrayList)3 DocStruct (ugh.dl.DocStruct)3 MetadataType (ugh.dl.MetadataType)3 ReadException (ugh.exceptions.ReadException)3 WriteException (ugh.exceptions.WriteException)3 Date (java.util.Date)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Step (org.goobi.beans.Step)2 JDOMException (org.jdom2.JDOMException)2 ContentFile (ugh.dl.ContentFile)2 Fileformat (ugh.dl.Fileformat)2 DocStructHasNoTypeException (ugh.exceptions.DocStructHasNoTypeException)2