Search in sources :

Example 36 with RepositoryHandler

use of org.olat.repository.handlers.RepositoryHandler in project OpenOLAT by OpenOLAT.

the class CourseWebService method getRepoFileById.

/**
 * Export the course
 * @response.representation.200.mediaType application/zip
 * @response.representation.200.doc The course as a ZIP file
 * @response.representation.401.doc Not authorized to export the course
 * @response.representation.404.doc The course not found
 * @return It returns the <code>CourseVO</code> object representing the course.
 */
@GET
@Path("file")
@Produces({ "application/zip", MediaType.APPLICATION_OCTET_STREAM })
public Response getRepoFileById(@Context HttpServletRequest request) {
    RepositoryService rs = CoreSpringFactory.getImpl(RepositoryService.class);
    RepositoryEntry re = course.getCourseEnvironment().getCourseGroupManager().getCourseEntry();
    if (re == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    RepositoryHandler typeToDownload = RepositoryHandlerFactory.getInstance().getRepositoryHandler(re);
    if (typeToDownload == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    Identity identity = getIdentity(request);
    boolean canDownload = re.getCanDownload() && typeToDownload.supportsDownload();
    if (isAdmin(request) || RepositoryManager.getInstance().isOwnerOfRepositoryEntry(identity, re)) {
        canDownload = true;
    } else if (!isAuthor(request)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    if (!canDownload) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    OLATResource ores = OLATResourceManager.getInstance().findResourceable(re.getOlatResource());
    if (ores == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    boolean isAlreadyLocked = typeToDownload.isLocked(ores);
    LockResult lockResult = null;
    try {
        lockResult = typeToDownload.acquireLock(ores, identity);
        if (lockResult == null || (lockResult != null && lockResult.isSuccess() && !isAlreadyLocked)) {
            MediaResource mr = typeToDownload.getAsMediaResource(ores, false);
            if (mr != null) {
                rs.incrementDownloadCounter(re);
                // success
                return Response.ok(mr.getInputStream()).cacheControl(cc).build();
            } else {
                return Response.serverError().status(Status.NO_CONTENT).build();
            }
        } else {
            return Response.serverError().status(Status.CONFLICT).build();
        }
    } finally {
        if ((lockResult != null && lockResult.isSuccess() && !isAlreadyLocked)) {
            typeToDownload.releaseLock(lockResult);
        }
    }
}
Also used : LockResult(org.olat.core.util.coordinate.LockResult) OLATResource(org.olat.resource.OLATResource) MediaResource(org.olat.core.gui.media.MediaResource) RepositoryEntry(org.olat.repository.RepositoryEntry) RepositoryHandler(org.olat.repository.handlers.RepositoryHandler) Identity(org.olat.core.id.Identity) RestSecurityHelper.getIdentity(org.olat.restapi.security.RestSecurityHelper.getIdentity) RepositoryService(org.olat.repository.RepositoryService) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 37 with RepositoryHandler

use of org.olat.repository.handlers.RepositoryHandler in project OpenOLAT by OpenOLAT.

the class RepositoryEntriesResource method importFileResource.

private RepositoryEntry importFileResource(Identity identity, File fResource, String resourcename, String displayname, String softkey, int access) {
    RepositoryService repositoryService = CoreSpringFactory.getImpl(RepositoryService.class);
    RepositoryHandlerFactory handlerFactory = CoreSpringFactory.getImpl(RepositoryHandlerFactory.class);
    try {
        RepositoryHandler handler = null;
        for (String type : handlerFactory.getSupportedTypes()) {
            RepositoryHandler h = handlerFactory.getRepositoryHandler(type);
            ResourceEvaluation eval = h.acceptImport(fResource, fResource.getName());
            if (eval != null && eval.isValid()) {
                handler = h;
                break;
            }
        }
        RepositoryEntry addedEntry = null;
        if (handler != null) {
            Locale locale = I18nModule.getDefaultLocale();
            addedEntry = handler.importResource(identity, null, displayname, "", true, locale, fResource, fResource.getName());
            if (StringHelper.containsNonWhitespace(resourcename)) {
                addedEntry.setResourcename(resourcename);
            }
            if (StringHelper.containsNonWhitespace(softkey)) {
                addedEntry.setSoftkey(softkey);
            }
            if (access < RepositoryEntry.ACC_OWNERS || access > RepositoryEntry.ACC_USERS_GUESTS) {
                addedEntry.setAccess(RepositoryEntry.ACC_OWNERS);
            } else {
                addedEntry.setAccess(access);
            }
            addedEntry = repositoryService.update(addedEntry);
        }
        return addedEntry;
    } catch (Exception e) {
        log.error("Fail to import a resource", e);
        throw new WebApplicationException(e);
    }
}
Also used : ResourceEvaluation(org.olat.fileresource.types.ResourceEvaluation) Locale(java.util.Locale) WebApplicationException(javax.ws.rs.WebApplicationException) RepositoryHandlerFactory(org.olat.repository.handlers.RepositoryHandlerFactory) RepositoryHandler(org.olat.repository.handlers.RepositoryHandler) RepositoryEntry(org.olat.repository.RepositoryEntry) WebApplicationException(javax.ws.rs.WebApplicationException) RepositoryService(org.olat.repository.RepositoryService)

Example 38 with RepositoryHandler

use of org.olat.repository.handlers.RepositoryHandler in project OpenOLAT by OpenOLAT.

the class RepositoryEntryImportExport method exportDoExportContent.

/**
 * Export a repository entry referenced by a course node to the given export directory.
 * User importReferencedRepositoryEntry to import again.
 * @return True upon success, false otherwise.
 */
public boolean exportDoExportContent() {
    // export resource
    RepositoryHandler rh = RepositoryHandlerFactory.getInstance().getRepositoryHandler(re);
    MediaResource mr = rh.getAsMediaResource(re.getOlatResource(), false);
    FileOutputStream fOut = null;
    try {
        fOut = new FileOutputStream(new File(baseDirectory, CONTENT_FILE));
        InputStream in = mr.getInputStream();
        if (in == null) {
            HttpServletResponse hres = new HttpServletResponseOutputStream(fOut);
            mr.prepare(hres);
        } else {
            IOUtils.copy(mr.getInputStream(), fOut);
        }
        fOut.flush();
    } catch (IOException fnfe) {
        return false;
    } finally {
        IOUtils.closeQuietly(fOut);
        mr.release();
    }
    return true;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) MediaResource(org.olat.core.gui.media.MediaResource) RepositoryHandler(org.olat.repository.handlers.RepositoryHandler) HttpServletResponseOutputStream(org.olat.core.util.io.HttpServletResponseOutputStream) IOException(java.io.IOException) File(java.io.File)

Example 39 with RepositoryHandler

use of org.olat.repository.handlers.RepositoryHandler in project OpenOLAT by OpenOLAT.

the class ImportRepositoryEntryController method doAnalyseUpload.

private void doAnalyseUpload() {
    File uploadedFile = uploadFileEl.getUploadFile();
    if (uploadedFile == null) {
        // OO-1320
        typeEl.setVisible(false);
        selectType.setVisible(false);
        uploadFileEl.reset();
        importButton.setEnabled(false);
    } else {
        String uploadedFilename = uploadFileEl.getUploadFileName();
        List<ResourceHandler> handlers = new ArrayList<>(3);
        for (String type : repositoryHandlerFactory.getSupportedTypes()) {
            RepositoryHandler handler = repositoryHandlerFactory.getRepositoryHandler(type);
            ResourceEvaluation eval = handler.acceptImport(uploadedFile, uploadedFilename);
            if (eval != null && eval.isValid()) {
                handlers.add(new ResourceHandler(handler, eval));
            }
        }
        updateResourceInfos(handlers);
        validLimitationOnType(handlers);
    }
}
Also used : ResourceEvaluation(org.olat.fileresource.types.ResourceEvaluation) ArrayList(java.util.ArrayList) RepositoryHandler(org.olat.repository.handlers.RepositoryHandler) File(java.io.File)

Example 40 with RepositoryHandler

use of org.olat.repository.handlers.RepositoryHandler in project OpenOLAT by OpenOLAT.

the class RepositoryEditDescriptionController method initForm.

@Override
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
    setFormContextHelp("Info Page: Add Meta Data");
    formLayout.setElementCssClass("o_sel_edit_repositoryentry");
    String id = repositoryEntry.getResourceableId() == null ? "-" : repositoryEntry.getResourceableId().toString();
    uifactory.addStaticTextElement("cif.id", id, formLayout);
    String externalId = repositoryEntry.getExternalId();
    if (StringHelper.containsNonWhitespace(externalId)) {
        uifactory.addStaticTextElement("cif.externalid", externalId, formLayout);
    }
    String extRef = repositoryEntry.getExternalRef();
    if (StringHelper.containsNonWhitespace(repositoryEntry.getManagedFlagsString())) {
        if (StringHelper.containsNonWhitespace(extRef)) {
            uifactory.addStaticTextElement("cif.externalref", extRef, formLayout);
        }
    } else {
        externalRef = uifactory.addTextElement("cif.externalref", "cif.externalref", 100, extRef, formLayout);
        externalRef.setHelpText(translate("cif.externalref.hover"));
        externalRef.setHelpUrlForManualPage("Info Page#_identification");
        externalRef.setDisplaySize(30);
    }
    String initalAuthor = repositoryEntry.getInitialAuthor() == null ? "-" : repositoryEntry.getInitialAuthor();
    if (repositoryEntry.getInitialAuthor() != null) {
        initalAuthor = userManager.getUserDisplayName(initalAuthor);
    }
    initalAuthor = StringHelper.escapeHtml(initalAuthor);
    uifactory.addStaticTextElement("cif.initialAuthor", initalAuthor, formLayout);
    // Add resource type
    String typeName = null;
    OLATResource res = repositoryEntry.getOlatResource();
    if (res != null) {
        typeName = res.getResourceableTypeName();
    }
    String typeDisplay;
    if (typeName != null) {
        // add image and typename code
        typeDisplay = NewControllerFactory.translateResourceableTypeName(typeName, getLocale());
    } else {
        typeDisplay = translate("cif.type.na");
    }
    uifactory.addStaticTextElement("cif.type", typeDisplay, formLayout);
    uifactory.addSpacerElement("spacer1", formLayout, false);
    displayName = uifactory.addTextElement("cif.displayname", "cif.displayname", 100, repositoryEntry.getDisplayname(), formLayout);
    displayName.setDisplaySize(30);
    displayName.setMandatory(true);
    displayName.setEnabled(!RepositoryEntryManagedFlag.isManaged(repositoryEntry, RepositoryEntryManagedFlag.title));
    authors = uifactory.addTextElement("cif.authors", "cif.authors", 255, repositoryEntry.getAuthors(), formLayout);
    authors.setDisplaySize(60);
    if (licenseModule.isEnabled(licenseHandler)) {
        license = licenseService.loadOrCreateLicense(res);
        LicenseSelectionConfig licenseSelectionConfig = LicenseUIFactory.createLicenseSelectionConfig(licenseHandler, license.getLicenseType());
        licenseEl = uifactory.addDropdownSingleselect("cif.license", formLayout, licenseSelectionConfig.getLicenseTypeKeys(), licenseSelectionConfig.getLicenseTypeValues(getLocale()));
        licenseEl.setElementCssClass("o_sel_repo_license");
        licenseEl.setMandatory(licenseSelectionConfig.isLicenseMandatory());
        if (licenseSelectionConfig.getSelectionLicenseTypeKey() != null) {
            licenseEl.select(licenseSelectionConfig.getSelectionLicenseTypeKey(), true);
        }
        licenseEl.addActionListener(FormEvent.ONCHANGE);
        licensorEl = uifactory.addTextElement("cif.licensor", 1000, license.getLicensor(), formLayout);
        String freetext = licenseService.isFreetext(license.getLicenseType()) ? license.getFreetext() : "";
        licenseFreetextEl = uifactory.addTextAreaElement("cif.freetext", 4, 72, freetext, formLayout);
        LicenseUIFactory.updateVisibility(licenseEl, licensorEl, licenseFreetextEl);
    }
    language = uifactory.addTextElement("cif.mainLanguage", "cif.mainLanguage", 16, repositoryEntry.getMainLanguage(), formLayout);
    location = uifactory.addTextElement("cif.location", "cif.location", 255, repositoryEntry.getLocation(), formLayout);
    location.setEnabled(!RepositoryEntryManagedFlag.isManaged(repositoryEntry, RepositoryEntryManagedFlag.location));
    RepositoryHandler handler = repositoryHandlerFactory.getRepositoryHandler(repositoryEntry);
    mediaContainer = handler.getMediaContainer(repositoryEntry);
    if (mediaContainer != null && mediaContainer.getName().equals("media")) {
        mediaContainer = mediaContainer.getParentContainer();
        mediaContainer.setDefaultItemFilter(new MediaContainerFilter(mediaContainer));
    }
    String desc = (repositoryEntry.getDescription() != null ? repositoryEntry.getDescription() : " ");
    description = uifactory.addRichTextElementForStringData("cif.description", "cif.description", desc, 10, -1, false, mediaContainer, null, formLayout, ureq.getUserSession(), getWindowControl());
    description.setEnabled(!RepositoryEntryManagedFlag.isManaged(repositoryEntry, RepositoryEntryManagedFlag.description));
    description.getEditorConfiguration().setFileBrowserUploadRelPath("media");
    uifactory.addSpacerElement("spacer2", formLayout, false);
    if (CourseModule.getCourseTypeName().equals(repoEntryType)) {
        String[] dateValues = new String[] { translate("cif.dates.none"), translate("cif.dates.private"), translate("cif.dates.public") };
        dateTypesEl = uifactory.addRadiosVertical("cif.dates", formLayout, dateKeys, dateValues);
        dateTypesEl.setElementCssClass("o_sel_repo_lifecycle_type");
        if (repositoryEntry.getLifecycle() == null) {
            dateTypesEl.select("none", true);
        } else if (repositoryEntry.getLifecycle().isPrivateCycle()) {
            dateTypesEl.select("private", true);
        } else {
            dateTypesEl.select("public", true);
        }
        dateTypesEl.addActionListener(FormEvent.ONCHANGE);
        List<RepositoryEntryLifecycle> cycles = lifecycleDao.loadPublicLifecycle();
        List<RepositoryEntryLifecycle> filteredCycles = new ArrayList<>();
        // just make the upcomming and acutual running cycles or the pre-selected visible in the UI
        LocalDateTime now = LocalDateTime.now();
        for (RepositoryEntryLifecycle cycle : cycles) {
            if (cycle.getValidTo() == null || now.isBefore(LocalDateTime.ofInstant(cycle.getValidTo().toInstant(), ZoneId.systemDefault())) || (repositoryEntry.getLifecycle() != null && repositoryEntry.getLifecycle().equals(cycle))) {
                filteredCycles.add(cycle);
            }
        }
        String[] publicKeys = new String[filteredCycles.size()];
        String[] publicValues = new String[filteredCycles.size()];
        int count = 0;
        for (RepositoryEntryLifecycle cycle : filteredCycles) {
            publicKeys[count] = cycle.getKey().toString();
            StringBuilder sb = new StringBuilder(32);
            boolean labelAvailable = StringHelper.containsNonWhitespace(cycle.getLabel());
            if (labelAvailable) {
                sb.append(cycle.getLabel());
            }
            if (StringHelper.containsNonWhitespace(cycle.getSoftKey())) {
                if (labelAvailable)
                    sb.append(" - ");
                sb.append(cycle.getSoftKey());
            }
            publicValues[count++] = sb.toString();
        }
        publicDatesEl = uifactory.addDropdownSingleselect("cif.public.dates", formLayout, publicKeys, publicValues, null);
        String privateDatePage = velocity_root + "/cycle_dates.html";
        privateDatesCont = FormLayoutContainer.createCustomFormLayout("private.date", getTranslator(), privateDatePage);
        privateDatesCont.setRootForm(mainForm);
        privateDatesCont.setLabel("cif.private.dates", null);
        formLayout.add("private.date", privateDatesCont);
        startDateEl = uifactory.addDateChooser("date.start", "cif.date.start", null, privateDatesCont);
        startDateEl.setElementCssClass("o_sel_repo_lifecycle_validfrom");
        endDateEl = uifactory.addDateChooser("date.end", "cif.date.end", null, privateDatesCont);
        endDateEl.setElementCssClass("o_sel_repo_lifecycle_validto");
        if (repositoryEntry.getLifecycle() != null) {
            RepositoryEntryLifecycle lifecycle = repositoryEntry.getLifecycle();
            if (lifecycle.isPrivateCycle()) {
                startDateEl.setDate(lifecycle.getValidFrom());
                endDateEl.setDate(lifecycle.getValidTo());
            } else {
                String key = lifecycle.getKey().toString();
                for (String publicKey : publicKeys) {
                    if (key.equals(publicKey)) {
                        publicDatesEl.select(key, true);
                        break;
                    }
                }
            }
        }
        updateDatesVisibility();
        uifactory.addSpacerElement("spacer3", formLayout, false);
        expenditureOfWork = uifactory.addTextElement("cif.expenditureOfWork", "cif.expenditureOfWork", 100, repositoryEntry.getExpenditureOfWork(), formLayout);
        expenditureOfWork.setExampleKey("details.expenditureOfWork.example", null);
        String obj = (repositoryEntry.getObjectives() != null ? repositoryEntry.getObjectives() : " ");
        objectives = uifactory.addRichTextElementForStringData("cif.objectives", "cif.objectives", obj, 10, -1, false, mediaContainer, null, formLayout, ureq.getUserSession(), getWindowControl());
        objectives.setEnabled(!RepositoryEntryManagedFlag.isManaged(repositoryEntry, RepositoryEntryManagedFlag.objectives));
        objectives.getEditorConfiguration().setFileBrowserUploadRelPath("media");
        String req = (repositoryEntry.getRequirements() != null ? repositoryEntry.getRequirements() : " ");
        requirements = uifactory.addRichTextElementForStringData("cif.requirements", "cif.requirements", req, 10, -1, false, mediaContainer, null, formLayout, ureq.getUserSession(), getWindowControl());
        requirements.setEnabled(!RepositoryEntryManagedFlag.isManaged(repositoryEntry, RepositoryEntryManagedFlag.requirements));
        requirements.getEditorConfiguration().setFileBrowserUploadRelPath("media");
        requirements.setMaxLength(2000);
        String cred = (repositoryEntry.getCredits() != null ? repositoryEntry.getCredits() : " ");
        credits = uifactory.addRichTextElementForStringData("cif.credits", "cif.credits", cred, 10, -1, false, mediaContainer, null, formLayout, ureq.getUserSession(), getWindowControl());
        credits.setEnabled(!RepositoryEntryManagedFlag.isManaged(repositoryEntry, RepositoryEntryManagedFlag.credits));
        credits.getEditorConfiguration().setFileBrowserUploadRelPath("media");
        credits.setMaxLength(2000);
        uifactory.addSpacerElement("spacer4", formLayout, false);
    }
    boolean managed = RepositoryEntryManagedFlag.isManaged(repositoryEntry, RepositoryEntryManagedFlag.details);
    VFSLeaf img = repositoryManager.getImage(repositoryEntry);
    fileUpload = uifactory.addFileElement(getWindowControl(), "rentry.pic", "rentry.pic", formLayout);
    fileUpload.setExampleKey("rentry.pic.example", new String[] { RepositoryManager.PICTURE_WIDTH + "x" + (RepositoryManager.PICTURE_HEIGHT) });
    fileUpload.setMaxUploadSizeKB(picUploadlimitKB, null, null);
    fileUpload.setPreview(ureq.getUserSession(), true);
    fileUpload.addActionListener(FormEvent.ONCHANGE);
    fileUpload.setDeleteEnabled(!managed);
    if (img instanceof LocalFileImpl) {
        fileUpload.setPreview(ureq.getUserSession(), true);
        fileUpload.setInitialFile(((LocalFileImpl) img).getBasefile());
    }
    fileUpload.setVisible(!managed);
    fileUpload.limitToMimeType(imageMimeTypes, "cif.error.mimetype", new String[] { imageMimeTypes.toString() });
    VFSLeaf movie = repositoryService.getIntroductionMovie(repositoryEntry);
    movieUpload = uifactory.addFileElement(getWindowControl(), "rentry.movie", "rentry.movie", formLayout);
    movieUpload.setExampleKey("rentry.movie.example", new String[] { "3:2" });
    movieUpload.setMaxUploadSizeKB(movieUploadlimitKB, null, null);
    movieUpload.setPreview(ureq.getUserSession(), true);
    movieUpload.addActionListener(FormEvent.ONCHANGE);
    movieUpload.setDeleteEnabled(!managed);
    if (movie instanceof LocalFileImpl) {
        movieUpload.setPreview(ureq.getUserSession(), true);
        movieUpload.setInitialFile(((LocalFileImpl) movie).getBasefile());
    }
    movieUpload.setVisible(!managed);
    FormLayoutContainer buttonContainer = FormLayoutContainer.createButtonLayout("buttonContainer", getTranslator());
    formLayout.add("buttonContainer", buttonContainer);
    buttonContainer.setElementCssClass("o_sel_repo_save_details");
    submit = uifactory.addFormSubmitButton("submit", buttonContainer);
    submit.setVisible(!managed);
    uifactory.addFormCancelButton("cancel", buttonContainer, ureq, getWindowControl());
}
Also used : LocalDateTime(java.time.LocalDateTime) VFSLeaf(org.olat.core.util.vfs.VFSLeaf) LicenseSelectionConfig(org.olat.core.commons.services.license.ui.LicenseSelectionConfig) ArrayList(java.util.ArrayList) OLATResource(org.olat.resource.OLATResource) LocalFileImpl(org.olat.core.util.vfs.LocalFileImpl) FormLayoutContainer(org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer) RepositoryEntryLifecycle(org.olat.repository.model.RepositoryEntryLifecycle) RepositoryHandler(org.olat.repository.handlers.RepositoryHandler)

Aggregations

RepositoryHandler (org.olat.repository.handlers.RepositoryHandler)74 RepositoryEntry (org.olat.repository.RepositoryEntry)42 RepositoryEntryImportExport (org.olat.repository.RepositoryEntryImportExport)18 OLATResource (org.olat.resource.OLATResource)16 File (java.io.File)14 ICourse (org.olat.course.ICourse)10 RepositoryService (org.olat.repository.RepositoryService)10 ArrayList (java.util.ArrayList)8 CloseableModalController (org.olat.core.gui.control.generic.closablewrapper.CloseableModalController)8 MediaResource (org.olat.core.gui.media.MediaResource)8 OLATResourceable (org.olat.core.id.OLATResourceable)8 FormLayoutContainer (org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer)6 LockResult (org.olat.core.util.coordinate.LockResult)6 VFSContainer (org.olat.core.util.vfs.VFSContainer)6 VFSLeaf (org.olat.core.util.vfs.VFSLeaf)6 OrderedRepositoryHandler (org.olat.repository.handlers.RepositoryHandlerFactory.OrderedRepositoryHandler)6 URL (java.net.URL)4 GET (javax.ws.rs.GET)4 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4