Search in sources :

Example 1 with LoginBean

use of org.goobi.managedbeans.LoginBean in project goobi-workflow by intranda.

the class ExportMets method startExport.

/**
 * DMS-Export in das Benutzer-Homeverzeichnis
 *
 * @param myProzess
 * @throws InterruptedException
 * @throws IOException
 * @throws DAOException
 * @throws SwapException
 * @throws ReadException
 * @throws UghHelperException
 * @throws ExportFileException
 * @throws MetadataTypeNotAllowedException
 * @throws WriteException
 * @throws PreferencesException
 * @throws DocStructHasNoTypeException
 * @throws TypeNotAllowedForParentException
 */
public boolean startExport(Process myProzess) throws IOException, InterruptedException, DocStructHasNoTypeException, PreferencesException, WriteException, MetadataTypeNotAllowedException, ExportFileException, UghHelperException, ReadException, SwapException, DAOException, TypeNotAllowedForParentException {
    String benutzerHome = "";
    LoginBean login = Helper.getLoginBean();
    if (login != null) {
        benutzerHome = login.getMyBenutzer().getHomeDir();
    } else {
        benutzerHome = myProzess.getProjekt().getDmsImportImagesPath();
    }
    return startExport(myProzess, benutzerHome);
}
Also used : LoginBean(org.goobi.managedbeans.LoginBean)

Example 2 with LoginBean

use of org.goobi.managedbeans.LoginBean 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 LoginBean

use of org.goobi.managedbeans.LoginBean in project goobi-workflow by intranda.

the class GoobiScript method execute.

public String execute(List<Integer> processes, List<Map<String, String>> scripts, GoobiScriptManager gsm) {
    if (scripts == null) {
        return "";
    }
    for (Map<String, String> currentScript : scripts) {
        // in case of a missing action parameter skip this goobiscript
        String myaction = currentScript.get("action");
        if (myaction == null || myaction.length() == 0) {
            Helper.setFehlerMeldung("goobiScriptfield", "Missing action!", "Please select one of the allowed commands.");
            continue;
        }
        // in case of missing rights skip this goobiscript
        LoginBean loginForm = Helper.getLoginBean();
        if (!loginForm.hasRole("goobiscript_" + myaction) && !loginForm.hasRole("Workflow_Processes_Allow_GoobiScript")) {
            Helper.setFehlerMeldung("goobiScriptfield", "You are not allowed to execute this GoobiScript: ", myaction);
            continue;
        }
        // now start the correct GoobiScript based on the String
        switch(myaction) {
            case "swapProzessesOut":
                swapOutProzesses(processes);
                break;
            case "swapProzessesIn":
                swapInProzesses(processes);
                break;
            case "updateContentFiles":
                updateContentFiles(processes);
                break;
            case "deleteTiffHeaderFile":
                deleteTiffHeaderFile(processes);
                break;
            default:
                // find the right GoobiScript class
                Optional<IGoobiScript> optGoobiScript = gsm.getGoobiScriptForAction(myaction);
                if (optGoobiScript.isPresent()) {
                    IGoobiScript gs = optGoobiScript.get();
                    // initialize the GoobiScript to check if all is valid
                    List<GoobiScriptResult> scriptResults = gs.prepare(processes, currentScript.toString(), currentScript);
                    // just execute the GoobiScript now if the initialization was valid
                    if (!scriptResults.isEmpty()) {
                        Helper.setMeldung("goobiScriptfield", "", "GoobiScript added: " + gs.getAction());
                        gsm.enqueueScripts(scriptResults);
                        gsm.startWork();
                    }
                } else {
                    Helper.setFehlerMeldung("goobiScriptfield", "Unknown action: " + myaction, " Please use one of the given below.");
                }
        }
    }
    return "";
}
Also used : LoginBean(org.goobi.managedbeans.LoginBean) IGoobiScript(org.goobi.goobiScript.IGoobiScript) GoobiScriptResult(org.goobi.goobiScript.GoobiScriptResult)

Example 4 with LoginBean

use of org.goobi.managedbeans.LoginBean in project goobi-workflow by intranda.

the class Helper method addMessageToProcessLog.

public static void addMessageToProcessLog(Integer processId, LogType type, String message) {
    LoginBean login = getLoginBean();
    String user = "- automatic -";
    if (login != null) {
        User userObject = login.getMyBenutzer();
        if (userObject != null) {
            user = userObject.getNachVorname();
        }
    }
    addMessageToProcessLog(processId, type, message, user);
}
Also used : User(org.goobi.beans.User) LoginBean(org.goobi.managedbeans.LoginBean)

Example 5 with LoginBean

use of org.goobi.managedbeans.LoginBean in project goobi-workflow by intranda.

the class Helper method getLoginBeanFromSession.

public static LoginBean getLoginBeanFromSession(HttpSession session) {
    Enumeration<String> attribs = session.getAttributeNames();
    String attrib;
    while (attribs.hasMoreElements()) {
        attrib = attribs.nextElement();
        Object obj = session.getAttribute(attrib);
        if (obj instanceof SerializableContextualInstanceImpl) {
            @SuppressWarnings("rawtypes") SerializableContextualInstanceImpl impl = (SerializableContextualInstanceImpl) obj;
            if (impl.getInstance() instanceof LoginBean) {
                return (LoginBean) impl.getInstance();
            }
        }
    }
    return null;
}
Also used : LoginBean(org.goobi.managedbeans.LoginBean) SerializableContextualInstanceImpl(org.jboss.weld.contexts.SerializableContextualInstanceImpl)

Aggregations

LoginBean (org.goobi.managedbeans.LoginBean)14 User (org.goobi.beans.User)5 AbstractTest (de.sub.goobi.AbstractTest)4 LogEntry (org.goobi.beans.LogEntry)4 Test (org.junit.Test)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 ConfigProjectsTest (de.sub.goobi.config.ConfigProjectsTest)3 MockProcess (de.sub.goobi.mock.MockProcess)3 Date (java.util.Date)3 Process (org.goobi.beans.Process)3 ConfigurationHelper (de.sub.goobi.config.ConfigurationHelper)2 DAOException (de.sub.goobi.helper.exceptions.DAOException)2 Operation (io.swagger.v3.oas.annotations.Operation)2 ApiResponse (io.swagger.v3.oas.annotations.responses.ApiResponse)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpSession (javax.servlet.http.HttpSession)2 Path (javax.ws.rs.Path)2 LogType (org.goobi.production.enums.LogType)2 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)1 ScriptThreadWithoutHibernate (de.sub.goobi.helper.ScriptThreadWithoutHibernate)1