Search in sources :

Example 1 with TypeNotAllowedAsChildException

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

the class MetadatenImagesHelper method createPagination.

/**
 * Markus baut eine Seitenstruktur aus den vorhandenen Images ---------------- Steps - ---------------- Validation of images compare existing
 * number images with existing number of page DocStructs if it is the same don't do anything if DocStructs are less add new pages to
 * physicalDocStruct if images are less delete pages from the end of pyhsicalDocStruct --------------------------------
 *
 * @return null
 * @throws TypeNotAllowedForParentException
 * @throws TypeNotAllowedForParentException
 * @throws InterruptedException
 * @throws IOException
 * @throws InterruptedException
 * @throws IOException
 * @throws DAOException
 * @throws SwapException
 */
public void createPagination(Process inProzess, String directory) throws TypeNotAllowedForParentException, IOException, InterruptedException, SwapException, DAOException {
    String mediaFolder = inProzess.getImagesTifDirectory(false);
    String mediaFolderWithFallback = inProzess.getImagesTifDirectory(true);
    DocStruct physicaldocstruct = this.mydocument.getPhysicalDocStruct();
    DocStruct logical = this.mydocument.getLogicalDocStruct();
    if (logical.getType().isAnchor()) {
        if (logical.getAllChildren() != null && logical.getAllChildren().size() > 0) {
            logical = logical.getAllChildren().get(0);
        }
    }
    MetadataType MDTypeForPath = this.myPrefs.getMetadataTypeByName("pathimagefiles");
    /*--------------------------------
         * der physische Baum wird nur
         * angelegt, wenn er noch nicht existierte
         * --------------------------------*/
    if (physicaldocstruct == null) {
        DocStructType dst = this.myPrefs.getDocStrctTypeByName("BoundBook");
        physicaldocstruct = this.mydocument.createDocStruct(dst);
        this.mydocument.setPhysicalDocStruct(physicaldocstruct);
    }
    // check for valid filepath
    try {
        List<? extends Metadata> filepath = physicaldocstruct.getAllMetadataByType(MDTypeForPath);
        if (filepath == null || filepath.isEmpty()) {
            Metadata mdForPath = new Metadata(MDTypeForPath);
            if (SystemUtils.IS_OS_WINDOWS) {
                mdForPath.setValue("file:/" + mediaFolder);
            } else {
                mdForPath.setValue("file://" + mediaFolder);
            }
            physicaldocstruct.addMetadata(mdForPath);
        }
    } catch (Exception e) {
        log.error(e);
    }
    Path folderToCheck = null;
    if (directory == null) {
        folderToCheck = Paths.get(mediaFolderWithFallback);
        checkIfImagesValid(inProzess.getTitel(), mediaFolderWithFallback);
    } else {
        folderToCheck = Paths.get(directory);
        if (!folderToCheck.isAbsolute()) {
            folderToCheck = Paths.get(inProzess.getImagesDirectory(), directory);
        }
        checkIfImagesValid(inProzess.getTitel(), folderToCheck.toString());
    }
    DocStructType typePage = this.myPrefs.getDocStrctTypeByName("page");
    DocStructType typeAudio = this.myPrefs.getDocStrctTypeByName("audio");
    DocStructType typeVideo = this.myPrefs.getDocStrctTypeByName("video");
    DocStructType type3dObject = this.myPrefs.getDocStrctTypeByName("object");
    // use fallback to 'page', if additional types are not configured in ruleset
    if (typeAudio == null) {
        typeAudio = typePage;
    }
    if (typeVideo == null) {
        typeVideo = typePage;
    }
    if (type3dObject == null) {
        type3dObject = typePage;
    }
    /*-------------------------------
         * retrieve existing pages/images
         * -------------------------------*/
    List<DocStruct> oldPages = physicaldocstruct.getAllChildren();
    if (oldPages == null) {
        oldPages = new ArrayList<>();
    }
    if (oldPages.size() == this.myLastImage) {
        return;
    }
    String defaultPagination = ConfigurationHelper.getInstance().getMetsEditorDefaultPagination();
    Map<String, DocStruct> assignedImages = new HashMap<>();
    List<DocStruct> pageElementsWithoutImages = new ArrayList<>();
    List<String> imagesWithoutPageElements = new ArrayList<>();
    if (physicaldocstruct.getAllChildren() != null && !physicaldocstruct.getAllChildren().isEmpty()) {
        List<String> imageFileList = null;
        imageFileList = StorageProvider.getInstance().list(folderToCheck.toString());
        Set<String> imageFileSet = new HashSet<>(imageFileList);
        for (DocStruct page : physicaldocstruct.getAllChildren()) {
            if (page.getImageName() != null) {
                if (imageFileSet.contains(page.getImageName())) {
                    assignedImages.put(page.getImageName(), page);
                } else {
                    try {
                        page.removeContentFile(page.getAllContentFiles().get(0));
                        pageElementsWithoutImages.add(page);
                    } catch (ContentFileNotLinkedException e) {
                        log.error(e);
                    }
                }
            } else {
                pageElementsWithoutImages.add(page);
            }
        }
    }
    try {
        List<String> imageNamesInMediaFolder = getDataFiles(inProzess, directory);
        if (imageNamesInMediaFolder != null && !imageNamesInMediaFolder.isEmpty()) {
            for (String imageName : imageNamesInMediaFolder) {
                if (!assignedImages.containsKey(imageName)) {
                    imagesWithoutPageElements.add(imageName);
                }
            }
        }
    } catch (InvalidImagesException e1) {
        log.error(e1);
    }
    // case 1: existing pages but no images (some images are removed)
    if (!pageElementsWithoutImages.isEmpty() && imagesWithoutPageElements.isEmpty()) {
        for (DocStruct pageToRemove : pageElementsWithoutImages) {
            physicaldocstruct.removeChild(pageToRemove);
            List<Reference> refs = new ArrayList<>(pageToRemove.getAllFromReferences());
            for (ugh.dl.Reference ref : refs) {
                DocStruct source = ref.getSource();
                for (Reference reference : source.getAllToReferences()) {
                    if (reference.getTarget().equals(pageToRemove)) {
                        source.getAllToReferences().remove(reference);
                        break;
                    }
                }
            }
        }
    } else // case 2: no page docs but images (some images are added)
    if (pageElementsWithoutImages.isEmpty() && !imagesWithoutPageElements.isEmpty()) {
        int currentPhysicalOrder = assignedImages.size();
        for (String newImage : imagesWithoutPageElements) {
            String mimetype = NIOFileUtils.getMimeTypeFromFile(Paths.get(newImage));
            DocStruct dsPage = null;
            if (mimetype.startsWith("image")) {
                dsPage = this.mydocument.createDocStruct(typePage);
            } else if (mimetype.startsWith("video") || mimetype.equals("application/mxf")) {
                dsPage = mydocument.createDocStruct(typeVideo);
            } else if (mimetype.startsWith("audio")) {
                dsPage = mydocument.createDocStruct(typeAudio);
            } else if (mimetype.startsWith("object")) {
                dsPage = mydocument.createDocStruct(type3dObject);
            } else if (mimetype.startsWith("model")) {
                dsPage = mydocument.createDocStruct(type3dObject);
            } else {
                // use old implementation as default
                dsPage = mydocument.createDocStruct(typePage);
            }
            try {
                // physical page no
                physicaldocstruct.addChild(dsPage);
                MetadataType mdt = this.myPrefs.getMetadataTypeByName("physPageNumber");
                Metadata mdTemp = new Metadata(mdt);
                mdTemp.setValue(String.valueOf(++currentPhysicalOrder));
                dsPage.addMetadata(mdTemp);
                // logical page no
                mdt = this.myPrefs.getMetadataTypeByName("logicalPageNumber");
                mdTemp = new Metadata(mdt);
                if (defaultPagination.equalsIgnoreCase("arabic")) {
                    mdTemp.setValue(String.valueOf(currentPhysicalOrder));
                } else if (defaultPagination.equalsIgnoreCase("roman")) {
                    RomanNumeral roman = new RomanNumeral();
                    roman.setValue(currentPhysicalOrder);
                    mdTemp.setValue(roman.getNumber());
                } else {
                    mdTemp.setValue("uncounted");
                }
                dsPage.addMetadata(mdTemp);
                logical.addReferenceTo(dsPage, "logical_physical");
                // image name
                ContentFile cf = new ContentFile();
                cf.setMimetype(mimetype);
                if (SystemUtils.IS_OS_WINDOWS) {
                    cf.setLocation("file:/" + mediaFolder + newImage);
                } else {
                    cf.setLocation("file://" + mediaFolder + newImage);
                }
                dsPage.addContentFile(cf);
            } catch (TypeNotAllowedAsChildException e) {
                log.error(e);
            } catch (MetadataTypeNotAllowedException e) {
                log.error(e);
            }
        }
    } else // case 3: empty page docs and unassinged images
    {
        for (DocStruct page : pageElementsWithoutImages) {
            if (!imagesWithoutPageElements.isEmpty()) {
                // assign new image name to page
                String newImageName = imagesWithoutPageElements.get(0);
                imagesWithoutPageElements.remove(0);
                ContentFile cf = new ContentFile();
                if (SystemUtils.IS_OS_WINDOWS) {
                    cf.setLocation("file:/" + mediaFolder + newImageName);
                } else {
                    cf.setLocation("file://" + mediaFolder + newImageName);
                }
                page.addContentFile(cf);
            } else {
                // remove page
                physicaldocstruct.removeChild(page);
                List<Reference> refs = new ArrayList<>(page.getAllFromReferences());
                for (ugh.dl.Reference ref : refs) {
                    ref.getSource().removeReferenceTo(page);
                }
            }
        }
        if (!imagesWithoutPageElements.isEmpty()) {
            // create new page elements
            int currentPhysicalOrder = physicaldocstruct.getAllChildren().size();
            for (String newImage : imagesWithoutPageElements) {
                String mimetype = NIOFileUtils.getMimeTypeFromFile(Paths.get(newImage));
                DocStruct dsPage = null;
                if (mimetype.startsWith("image")) {
                    dsPage = this.mydocument.createDocStruct(typePage);
                } else if (mimetype.startsWith("video") || mimetype.equals("application/mxf")) {
                    dsPage = mydocument.createDocStruct(typeVideo);
                } else if (mimetype.startsWith("audio")) {
                    dsPage = mydocument.createDocStruct(typeAudio);
                } else if (mimetype.startsWith("object")) {
                    dsPage = mydocument.createDocStruct(type3dObject);
                } else if (mimetype.startsWith("model")) {
                    dsPage = mydocument.createDocStruct(type3dObject);
                } else {
                    // use old implementation as default
                    dsPage = mydocument.createDocStruct(typePage);
                }
                try {
                    // physical page no
                    physicaldocstruct.addChild(dsPage);
                    MetadataType mdt = this.myPrefs.getMetadataTypeByName("physPageNumber");
                    Metadata mdTemp = new Metadata(mdt);
                    mdTemp.setValue(String.valueOf(++currentPhysicalOrder));
                    dsPage.addMetadata(mdTemp);
                    // logical page no
                    mdt = this.myPrefs.getMetadataTypeByName("logicalPageNumber");
                    mdTemp = new Metadata(mdt);
                    if (defaultPagination.equalsIgnoreCase("arabic")) {
                        mdTemp.setValue(String.valueOf(currentPhysicalOrder));
                    } else if (defaultPagination.equalsIgnoreCase("roman")) {
                        RomanNumeral roman = new RomanNumeral();
                        roman.setValue(currentPhysicalOrder);
                        mdTemp.setValue(roman.getNumber());
                    } else {
                        mdTemp.setValue("uncounted");
                    }
                    dsPage.addMetadata(mdTemp);
                    logical.addReferenceTo(dsPage, "logical_physical");
                    // image name
                    ContentFile cf = new ContentFile();
                    cf.setMimetype(mimetype);
                    if (SystemUtils.IS_OS_WINDOWS) {
                        cf.setLocation("file:/" + mediaFolder + newImage);
                    } else {
                        cf.setLocation("file://" + mediaFolder + newImage);
                    }
                    dsPage.addContentFile(cf);
                } catch (TypeNotAllowedAsChildException e) {
                    log.error(e);
                } catch (MetadataTypeNotAllowedException e) {
                    log.error(e);
                }
            }
        }
    }
    int currentPhysicalOrder = 1;
    MetadataType mdt = this.myPrefs.getMetadataTypeByName("physPageNumber");
    if (physicaldocstruct.getAllChildren() != null) {
        for (DocStruct page : physicaldocstruct.getAllChildren()) {
            List<? extends Metadata> pageNoMetadata = page.getAllMetadataByType(mdt);
            if (pageNoMetadata == null || pageNoMetadata.size() == 0) {
                currentPhysicalOrder++;
                break;
            }
            for (Metadata pageNo : pageNoMetadata) {
                pageNo.setValue(String.valueOf(currentPhysicalOrder));
            }
            currentPhysicalOrder++;
        }
    }
}
Also used : RomanNumeral(ugh.dl.RomanNumeral) ContentFile(ugh.dl.ContentFile) HashMap(java.util.HashMap) Metadata(ugh.dl.Metadata) ArrayList(java.util.ArrayList) ContentFileNotLinkedException(ugh.exceptions.ContentFileNotLinkedException) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) DocStruct(ugh.dl.DocStruct) HashSet(java.util.HashSet) Path(java.nio.file.Path) TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) Reference(ugh.dl.Reference) MetadataType(ugh.dl.MetadataType) Reference(ugh.dl.Reference) URISyntaxException(java.net.URISyntaxException) TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) DAOException(de.sub.goobi.helper.exceptions.DAOException) SwapException(de.sub.goobi.helper.exceptions.SwapException) ContentLibException(de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) ImageManipulatorException(de.unigoettingen.sub.commons.contentlib.exceptions.ImageManipulatorException) ImageManagerException(de.unigoettingen.sub.commons.contentlib.exceptions.ImageManagerException) IOException(java.io.IOException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) InvalidImagesException(de.sub.goobi.helper.exceptions.InvalidImagesException) ContentFileNotLinkedException(ugh.exceptions.ContentFileNotLinkedException) InvalidImagesException(de.sub.goobi.helper.exceptions.InvalidImagesException) DocStructType(ugh.dl.DocStructType) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException)

Example 2 with TypeNotAllowedAsChildException

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

the class Metadaten method addPageAreaCommand.

/**
 * Add page area via commandScript
 */
public void addPageAreaCommand() {
    String addTo = getRequestParameter("addTo");
    Integer x = Integer.parseInt(getRequestParameter("x"));
    Integer y = Integer.parseInt(getRequestParameter("y"));
    Integer w = Integer.parseInt(getRequestParameter("w"));
    Integer h = Integer.parseInt(getRequestParameter("h"));
    DocStruct page = getCurrentPage();
    DocStruct logicalDocStruct = "current".equalsIgnoreCase(addTo) ? this.myDocStruct : null;
    try {
        DocStruct pageArea = this.pageAreaManager.createPageArea(page, x, y, w, h);
        if (logicalDocStruct != null) {
            this.pageAreaManager.assignToPhysicalDocStruct(pageArea, page);
            this.pageAreaManager.assignToLogicalDocStruct(pageArea, logicalDocStruct);
            retrieveAllImages();
        } else {
            this.pageAreaManager.setNewPageArea(pageArea);
        }
    } catch (TypeNotAllowedAsChildException | TypeNotAllowedForParentException | MetadataTypeNotAllowedException e) {
        log.error(e);
    }
}
Also used : TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) DocStruct(ugh.dl.DocStruct)

Example 3 with TypeNotAllowedAsChildException

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

the class Metadaten method ChangeCurrentDocstructType.

public String ChangeCurrentDocstructType() {
    if (this.myDocStruct != null && this.tempWert != null) {
        try {
            DocStruct rueckgabe = this.metahelper.ChangeCurrentDocstructType(this.myDocStruct, this.tempWert);
            MetadatenalsBeanSpeichern(rueckgabe);
            MetadatenalsTree3Einlesen1(this.tree3, this.currentTopstruct, false);
        } catch (DocStructHasNoTypeException | MetadataTypeNotAllowedException | TypeNotAllowedAsChildException | TypeNotAllowedForParentException e) {
            Helper.setFehlerMeldung("Error while changing DocStructTypes: ", e.getMessage());
            log.error("Error while changing DocStructTypes: " + e);
        }
    }
    return "metseditor";
}
Also used : TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) DocStructHasNoTypeException(ugh.exceptions.DocStructHasNoTypeException) DocStruct(ugh.dl.DocStruct)

Example 4 with TypeNotAllowedAsChildException

use of ugh.exceptions.TypeNotAllowedAsChildException 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 5 with TypeNotAllowedAsChildException

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

the class MetadatenHelper method ChangeCurrentDocstructType.

/* =============================================================== */
public DocStruct ChangeCurrentDocstructType(DocStruct inOldDocstruct, String inNewType) throws DocStructHasNoTypeException, MetadataTypeNotAllowedException, TypeNotAllowedAsChildException, TypeNotAllowedForParentException {
    // inOldDocstruct.getType().getName()
    // + " soll werden zu " + inNewType);
    DocStructType dst = this.myPrefs.getDocStrctTypeByName(inNewType);
    DocStruct newDocstruct = this.mydocument.createDocStruct(dst);
    /*
         * -------------------------------- alle Metadaten hinzufügen --------------------------------
         */
    if (inOldDocstruct.getAllMetadata() != null && inOldDocstruct.getAllMetadata().size() > 0) {
        for (Metadata old : inOldDocstruct.getAllMetadata()) {
            boolean match = false;
            if (old.getValue() != null && !old.getValue().isEmpty()) {
                if (newDocstruct.getAddableMetadataTypes(true) != null && newDocstruct.getAddableMetadataTypes(true).size() > 0) {
                    for (MetadataType mt : newDocstruct.getAddableMetadataTypes(true)) {
                        if (mt.getName().equals(old.getType().getName())) {
                            match = true;
                            break;
                        }
                    }
                    if (!match) {
                        try {
                            newDocstruct.addMetadata(old);
                        } catch (Exception e) {
                            Helper.setFehlerMeldung("Metadata " + old.getType().getName() + " is not allowed in new element " + newDocstruct.getType().getName());
                            return inOldDocstruct;
                        }
                    } else {
                        newDocstruct.addMetadata(old);
                    }
                } else {
                    Helper.setFehlerMeldung("Metadata " + old.getType().getName() + " is not allowed in new element " + newDocstruct.getType().getName());
                    return inOldDocstruct;
                }
            }
        }
    }
    /*
         * -------------------------------- alle Personen hinzufügen --------------------------------
         */
    if (inOldDocstruct.getAllPersons() != null && inOldDocstruct.getAllPersons().size() > 0) {
        for (Person old : inOldDocstruct.getAllPersons()) {
            boolean match = false;
            if ((old.getFirstname() != null && !old.getFirstname().isEmpty()) || (old.getLastname() != null && !old.getLastname().isEmpty())) {
                if (newDocstruct.getAddableMetadataTypes(true) != null && newDocstruct.getAddableMetadataTypes(true).size() > 0) {
                    for (MetadataType mt : newDocstruct.getAddableMetadataTypes(true)) {
                        if (mt.getName().equals(old.getType().getName())) {
                            match = true;
                            break;
                        }
                    }
                    if (!match) {
                        Helper.setFehlerMeldung("Person " + old.getType().getName() + " is not allowed in new element " + newDocstruct.getType().getName());
                    } else {
                        newDocstruct.addPerson(old);
                    }
                } else {
                    Helper.setFehlerMeldung("Person " + old.getType().getName() + " is not allowed in new element " + newDocstruct.getType().getName());
                    return inOldDocstruct;
                }
            }
        }
    }
    if (inOldDocstruct.getAllMetadataGroups() != null && inOldDocstruct.getAllMetadataGroups().size() > 0) {
        for (MetadataGroup mg : inOldDocstruct.getAllMetadataGroups()) {
            boolean match = false;
            if (newDocstruct.getPossibleMetadataGroupTypes() != null && newDocstruct.getPossibleMetadataGroupTypes().size() > 0) {
                for (MetadataGroupType mgt : newDocstruct.getPossibleMetadataGroupTypes()) {
                    if (mgt.getName().equals(mg.getType().getName())) {
                        match = true;
                        break;
                    }
                }
                if (!match) {
                    Helper.setFehlerMeldung("Person " + mg.getType().getName() + " is not allowed in new element " + newDocstruct.getType().getName());
                } else {
                    newDocstruct.addMetadataGroup(mg);
                }
            } else {
                Helper.setFehlerMeldung("Person " + mg.getType().getName() + " is not allowed in new element " + newDocstruct.getType().getName());
                return inOldDocstruct;
            }
        }
    }
    /*
         * -------------------------------- alle Seiten hinzufügen --------------------------------
         */
    if (inOldDocstruct.getAllToReferences() != null) {
        for (Reference p : inOldDocstruct.getAllToReferences()) {
            newDocstruct.addReferenceTo(p.getTarget(), p.getType());
        }
    }
    /*
         * -------------------------------- alle Docstruct-Children hinzufügen --------------------------------
         */
    if (inOldDocstruct.getAllChildren() != null && inOldDocstruct.getAllChildren().size() > 0) {
        for (DocStruct old : inOldDocstruct.getAllChildren()) {
            if (newDocstruct.getType().getAllAllowedDocStructTypes() != null && newDocstruct.getType().getAllAllowedDocStructTypes().size() > 0) {
                if (!newDocstruct.getType().getAllAllowedDocStructTypes().contains(old.getType().getName())) {
                    Helper.setFehlerMeldung("Child element " + old.getType().getName() + " is not allowed in new element " + newDocstruct.getType().getName());
                    return inOldDocstruct;
                } else {
                    newDocstruct.addChild(old);
                }
            } else {
                Helper.setFehlerMeldung("Child element " + old.getType().getName() + " is not allowed in new element " + newDocstruct.getType().getName());
                return inOldDocstruct;
            }
        }
    }
    /*
         * -------------------------------- neues Docstruct zum Parent hinzufügen und an die gleiche Stelle schieben, wie den Vorg?nger
         * --------------------------------
         */
    // int index = 0;
    // for (DocStruct ds : inOldDocstruct.getParent().getAllChildren()) {
    // index++;
    // if (ds.equals(inOldDocstruct)) {
    // break;
    // }
    // }
    newDocstruct.setParent(inOldDocstruct.getParent());
    int index = inOldDocstruct.getParent().getAllChildren().indexOf(inOldDocstruct);
    inOldDocstruct.getParent().getAllChildren().add(index, newDocstruct);
    /*
         * -------------------------------- altes Docstruct vom Parent entfernen und neues als aktuelles nehmen --------------------------------
         */
    inOldDocstruct.getParent().removeChild(inOldDocstruct);
    return newDocstruct;
}
Also used : MetadataGroupType(ugh.dl.MetadataGroupType) DocStructType(ugh.dl.DocStructType) Reference(ugh.dl.Reference) Metadata(ugh.dl.Metadata) MetadataType(ugh.dl.MetadataType) MetadataGroup(ugh.dl.MetadataGroup) Person(ugh.dl.Person) DocStruct(ugh.dl.DocStruct) TypeNotAllowedAsChildException(ugh.exceptions.TypeNotAllowedAsChildException) TypeNotAllowedForParentException(ugh.exceptions.TypeNotAllowedForParentException) IOException(java.io.IOException) MetadataTypeNotAllowedException(ugh.exceptions.MetadataTypeNotAllowedException) PreferencesException(ugh.exceptions.PreferencesException) InvocationTargetException(java.lang.reflect.InvocationTargetException) DocStructHasNoTypeException(ugh.exceptions.DocStructHasNoTypeException)

Aggregations

DocStruct (ugh.dl.DocStruct)5 MetadataTypeNotAllowedException (ugh.exceptions.MetadataTypeNotAllowedException)5 TypeNotAllowedAsChildException (ugh.exceptions.TypeNotAllowedAsChildException)5 TypeNotAllowedForParentException (ugh.exceptions.TypeNotAllowedForParentException)5 IOException (java.io.IOException)3 Metadata (ugh.dl.Metadata)3 MetadataType (ugh.dl.MetadataType)3 DocStructHasNoTypeException (ugh.exceptions.DocStructHasNoTypeException)3 DAOException (de.sub.goobi.helper.exceptions.DAOException)2 SwapException (de.sub.goobi.helper.exceptions.SwapException)2 Path (java.nio.file.Path)2 DocStructType (ugh.dl.DocStructType)2 Reference (ugh.dl.Reference)2 PreferencesException (ugh.exceptions.PreferencesException)2 ScriptThreadWithoutHibernate (de.sub.goobi.helper.ScriptThreadWithoutHibernate)1 InvalidImagesException (de.sub.goobi.helper.exceptions.InvalidImagesException)1 UghHelperException (de.sub.goobi.helper.exceptions.UghHelperException)1 ContentLibException (de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException)1 ImageManagerException (de.unigoettingen.sub.commons.contentlib.exceptions.ImageManagerException)1 ImageManipulatorException (de.unigoettingen.sub.commons.contentlib.exceptions.ImageManipulatorException)1