Search in sources :

Example 1 with MCRConfiguration2

use of org.mycore.common.config.MCRConfiguration2 in project mycore by MyCoRe-Org.

the class MCRThumbnailResource method getThumbnail.

private Response getThumbnail(String documentId, int size, String ext) {
    List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(MCRJerseyUtil.getID(documentId), 1, TimeUnit.MINUTES);
    for (MCRObjectID derivateId : derivateIds) {
        if (MCRAccessManager.checkPermissionForReadingDerivate(derivateId.toString())) {
            String nameOfMainFile = MCRMetadataManager.retrieveMCRDerivate(derivateId).getDerivate().getInternals().getMainDoc();
            if (nameOfMainFile != null && !nameOfMainFile.equals("")) {
                MCRPath mainFile = MCRPath.getPath(derivateId.toString(), '/' + nameOfMainFile);
                try {
                    FileTime lastModified = Files.getLastModifiedTime(mainFile);
                    Date lastModifiedDate = new Date(lastModified.toMillis());
                    Response.ResponseBuilder resp = request.evaluatePreconditions(lastModifiedDate);
                    if (resp != null) {
                        return resp.build();
                    }
                    String mimeType = Files.probeContentType(mainFile);
                    List<MCRThumbnailGenerator> generators = MCRConfiguration2.getOrThrow("MCR.Media.Thumbnail.Generators", MCRConfiguration2::splitValue).map(MCRConfiguration2::<MCRThumbnailGenerator>instantiateClass).filter(thumbnailGenerator -> thumbnailGenerator.matchesFileType(mimeType, mainFile)).collect(Collectors.toList());
                    final Optional<BufferedImage> thumbnail = generators.stream().map(thumbnailGenerator -> {
                        try {
                            return thumbnailGenerator.getThumbnail(mainFile, size);
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    }).filter(Optional::isPresent).map(Optional::get).findFirst();
                    if (thumbnail.isPresent()) {
                        CacheControl cc = new CacheControl();
                        cc.setMaxAge((int) TimeUnit.DAYS.toSeconds(1));
                        String type = "image/png";
                        if ("jpg".equals(ext) || "jpeg".equals(ext)) {
                            type = "image/jpeg";
                        }
                        return Response.ok(thumbnail.get()).cacheControl(cc).lastModified(lastModifiedDate).type(type).build();
                    }
                } catch (IOException | RuntimeException e) {
                    throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
                }
            }
        }
    }
    return Response.status(Response.Status.NOT_FOUND).build();
}
Also used : MCRJerseyUtil(org.mycore.frontend.jersey.MCRJerseyUtil) Context(jakarta.ws.rs.core.Context) Date(java.util.Date) FileTime(java.nio.file.attribute.FileTime) GET(jakarta.ws.rs.GET) WebApplicationException(jakarta.ws.rs.WebApplicationException) MCRAccessManager(org.mycore.access.MCRAccessManager) Path(jakarta.ws.rs.Path) Response(jakarta.ws.rs.core.Response) Produces(jakarta.ws.rs.Produces) Request(jakarta.ws.rs.core.Request) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) CacheControl(jakarta.ws.rs.core.CacheControl) BufferedImage(java.awt.image.BufferedImage) Files(java.nio.file.Files) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) UncheckedIOException(java.io.UncheckedIOException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRThumbnailGenerator(org.mycore.media.services.MCRThumbnailGenerator) Optional(java.util.Optional) PathParam(jakarta.ws.rs.PathParam) MCRThumbnailGenerator(org.mycore.media.services.MCRThumbnailGenerator) Optional(java.util.Optional) WebApplicationException(jakarta.ws.rs.WebApplicationException) FileTime(java.nio.file.attribute.FileTime) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Date(java.util.Date) BufferedImage(java.awt.image.BufferedImage) Response(jakarta.ws.rs.core.Response) MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) CacheControl(jakarta.ws.rs.core.CacheControl) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 2 with MCRConfiguration2

use of org.mycore.common.config.MCRConfiguration2 in project mycore by MyCoRe-Org.

the class MCREditorOutValidator method getValidatorMap.

private static Map<String, MCREditorMetadataValidator> getValidatorMap() {
    Map<String, MCREditorMetadataValidator> map = new HashMap<>();
    map.put(MCRMetaBoolean.class.getSimpleName(), getObjectCheckInstance(MCRMetaBoolean.class));
    map.put(MCRMetaPersonName.class.getSimpleName(), getObjectCheckWithLangInstance(MCRMetaPersonName.class));
    map.put(MCRMetaInstitutionName.class.getSimpleName(), getObjectCheckWithLangInstance(MCRMetaInstitutionName.class));
    map.put(MCRMetaAddress.class.getSimpleName(), new MCRMetaAdressCheck());
    map.put(MCRMetaNumber.class.getSimpleName(), getObjectCheckWithLangNotEmptyInstance(MCRMetaNumber.class));
    map.put(MCRMetaLinkID.class.getSimpleName(), getObjectCheckWithLinksInstance(MCRMetaLinkID.class));
    map.put(MCRMetaEnrichedLinkID.class.getSimpleName(), getObjectCheckWithLinksInstance(MCRMetaEnrichedLinkID.class));
    map.put(MCRMetaDerivateLink.class.getSimpleName(), getObjectCheckWithLinksInstance(MCRMetaDerivateLink.class));
    map.put(MCRMetaLink.class.getSimpleName(), getObjectCheckWithLinksInstance(MCRMetaLink.class));
    map.put(MCRMetaISO8601Date.class.getSimpleName(), getObjectCheckWithLangNotEmptyInstance(MCRMetaISO8601Date.class));
    map.put(MCRMetaLangText.class.getSimpleName(), getObjectCheckWithLangNotEmptyInstance(MCRMetaLangText.class));
    map.put(MCRMetaAccessRule.class.getSimpleName(), getObjectCheckInstance(MCRMetaAccessRule.class));
    map.put(MCRMetaClassification.class.getSimpleName(), new MCRMetaClassificationCheck());
    map.put(MCRMetaHistoryDate.class.getSimpleName(), new MCRMetaHistoryDateCheck());
    Map<String, String> props = MCRConfiguration2.getPropertiesMap().entrySet().stream().filter(p -> p.getKey().startsWith(CONFIG_PREFIX + "class.")).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    for (Entry<String, String> entry : props.entrySet()) {
        try {
            String className = entry.getKey();
            className = className.substring(className.lastIndexOf('.') + 1);
            LOGGER.info("Adding Validator {} for class {}", entry.getValue(), className);
            @SuppressWarnings("unchecked") Class<? extends MCREditorMetadataValidator> cl = (Class<? extends MCREditorMetadataValidator>) Class.forName(entry.getValue());
            map.put(className, cl.getDeclaredConstructor().newInstance());
        } catch (Exception e) {
            final String msg = "Cannot instantiate " + entry.getValue() + " as validator for class " + entry.getKey();
            LOGGER.error(msg);
            throw new MCRException(msg, e);
        }
    }
    return map;
}
Also used : MCRMetaClassification(org.mycore.datamodel.metadata.MCRMetaClassification) MCRMetaISO8601Date(org.mycore.datamodel.metadata.MCRMetaISO8601Date) MCRMetaAddress(org.mycore.datamodel.metadata.MCRMetaAddress) MCRMetaInstitutionName(org.mycore.datamodel.metadata.MCRMetaInstitutionName) MCRMetaLink(org.mycore.datamodel.metadata.MCRMetaLink) Document(org.jdom2.Document) XSI_NAMESPACE(org.mycore.common.MCRConstants.XSI_NAMESPACE) JDOMException(org.jdom2.JDOMException) XLINK_NAMESPACE(org.mycore.common.MCRConstants.XLINK_NAMESPACE) Map(java.util.Map) MCRMetaInterface(org.mycore.datamodel.metadata.MCRMetaInterface) MCRClassTools(org.mycore.common.MCRClassTools) XML_NAMESPACE(org.jdom2.Namespace.XML_NAMESPACE) Format(org.jdom2.output.Format) Collection(java.util.Collection) MCRMetaEnrichedLinkID(org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID) MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) MCRMetaBoolean(org.mycore.datamodel.metadata.MCRMetaBoolean) Collectors(java.util.stream.Collectors) MCRMetaHistoryDate(org.mycore.datamodel.metadata.MCRMetaHistoryDate) MCRUtils(org.mycore.common.MCRUtils) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) Entry(java.util.Map.Entry) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) Element(org.jdom2.Element) MCRJDOMContent(org.mycore.common.content.MCRJDOMContent) MCRMetaLangText(org.mycore.datamodel.metadata.MCRMetaLangText) MCRMetaAccessRule(org.mycore.datamodel.metadata.MCRMetaAccessRule) XPathFactory(org.jdom2.xpath.XPathFactory) HashMap(java.util.HashMap) MCRException(org.mycore.common.MCRException) ArrayList(java.util.ArrayList) MCRAccessManager(org.mycore.access.MCRAccessManager) MCRMetaDerivateLink(org.mycore.datamodel.metadata.MCRMetaDerivateLink) MCRMetaPersonName(org.mycore.datamodel.metadata.MCRMetaPersonName) SAXBuilder(org.jdom2.input.SAXBuilder) Iterator(java.util.Iterator) MCRRuleAccessInterface(org.mycore.access.MCRRuleAccessInterface) MCRMetaNumber(org.mycore.datamodel.metadata.MCRMetaNumber) IOException(java.io.IOException) XMLOutputter(org.jdom2.output.XMLOutputter) Attribute(org.jdom2.Attribute) SAXParseException(org.xml.sax.SAXParseException) MCRSessionMgr(org.mycore.common.MCRSessionMgr) MCRObject(org.mycore.datamodel.metadata.MCRObject) LogManager(org.apache.logging.log4j.LogManager) Filters(org.jdom2.filter.Filters) InputStream(java.io.InputStream) MCRMetaISO8601Date(org.mycore.datamodel.metadata.MCRMetaISO8601Date) MCRMetaLangText(org.mycore.datamodel.metadata.MCRMetaLangText) HashMap(java.util.HashMap) MCRMetaClassification(org.mycore.datamodel.metadata.MCRMetaClassification) MCRMetaInstitutionName(org.mycore.datamodel.metadata.MCRMetaInstitutionName) MCRMetaNumber(org.mycore.datamodel.metadata.MCRMetaNumber) MCRMetaLink(org.mycore.datamodel.metadata.MCRMetaLink) MCRMetaBoolean(org.mycore.datamodel.metadata.MCRMetaBoolean) MCRMetaAccessRule(org.mycore.datamodel.metadata.MCRMetaAccessRule) MCRMetaHistoryDate(org.mycore.datamodel.metadata.MCRMetaHistoryDate) MCRMetaPersonName(org.mycore.datamodel.metadata.MCRMetaPersonName) MCRMetaAddress(org.mycore.datamodel.metadata.MCRMetaAddress) MCRException(org.mycore.common.MCRException) MCRMetaDerivateLink(org.mycore.datamodel.metadata.MCRMetaDerivateLink) MCRMetaEnrichedLinkID(org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID) JDOMException(org.jdom2.JDOMException) MCRException(org.mycore.common.MCRException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID)

Example 3 with MCRConfiguration2

use of org.mycore.common.config.MCRConfiguration2 in project mycore by MyCoRe-Org.

the class MCRJWTUtil method getJWTBuilder.

public static JWTCreator.Builder getJWTBuilder(MCRSession mcrSession, String[] userAttributes, String[] sessionAttributes) {
    MCRUserInformation userInformation = mcrSession.getUserInformation();
    String[] roles = MCRConfiguration2.getOrThrow(ROLES_PROPERTY, MCRConfiguration2::splitValue).filter(userInformation::isUserInRole).toArray(String[]::new);
    String subject = userInformation.getUserID();
    String email = userInformation.getUserAttribute(MCRUserInformation.ATT_EMAIL);
    String name = userInformation.getUserAttribute(MCRUserInformation.ATT_REAL_NAME);
    JWTCreator.Builder builder = JWT.create().withIssuedAt(new Date()).withSubject(subject).withArrayClaim("mcr:roles", roles).withClaim("email", email).withClaim("name", name);
    if (userAttributes != null) {
        for (String userAttribute : userAttributes) {
            String value = userInformation.getUserAttribute(userAttribute);
            if (value != null) {
                builder.withClaim(JWT_USER_ATTRIBUTE_PREFIX + userAttribute, value);
            }
        }
    }
    if (sessionAttributes != null) {
        for (String sessionAttribute : sessionAttributes) {
            Object object = mcrSession.get(sessionAttribute);
            Optional.ofNullable(object).map(Object::toString).ifPresent((value) -> {
                builder.withClaim(JWT_SESSION_ATTRIBUTE_PREFIX + sessionAttribute, value);
            });
        }
    }
    return builder;
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) MCRUserInformation(org.mycore.common.MCRUserInformation) Date(java.util.Date)

Example 4 with MCRConfiguration2

use of org.mycore.common.config.MCRConfiguration2 in project mycore by MyCoRe-Org.

the class MCRSword method initWorkspaceCollection.

private static void initWorkspaceCollection(String workspace, String collection) {
    LOGGER.info("Found collection: {} in workspace {}", collection, workspace);
    String name = MCRSwordConstants.MCR_SWORD_COLLECTION_PREFIX + workspace + "." + collection;
    LOGGER.info("Try to init : {}", name);
    MCRSwordCollectionProvider collectionProvider = MCRConfiguration2.getOrThrow(name, MCRConfiguration2::instantiateClass);
    collections.put(collection, collectionProvider);
    final MCRSwordLifecycleConfiguration lifecycleConfiguration = new MCRSwordLifecycleConfiguration(collection);
    collectionProvider.init(lifecycleConfiguration);
    List<String> collectionsOfWorkspace;
    if (workspaceCollectionTable.containsKey(workspace)) {
        collectionsOfWorkspace = workspaceCollectionTable.get(workspace);
    } else {
        collectionsOfWorkspace = new ArrayList<>();
        workspaceCollectionTable.put(workspace, collectionsOfWorkspace);
    }
    collectionsOfWorkspace.add(collection);
}
Also used : MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) MCRSwordCollectionProvider(org.mycore.sword.application.MCRSwordCollectionProvider) MCRSwordLifecycleConfiguration(org.mycore.sword.application.MCRSwordLifecycleConfiguration)

Example 5 with MCRConfiguration2

use of org.mycore.common.config.MCRConfiguration2 in project mycore by MyCoRe-Org.

the class MCRDOICommands method synchronizeDatabase.

@MCRCommand(syntax = "repair registered dois {0}", help = "Contacts the Registration Service and inserts all registered DOIs to the Database. " + "It also updates all media files. The Service ID{0} is the id from the configuration.", order = 10)
public static void synchronizeDatabase(String serviceID) {
    MCRDOIService registrationService = (MCRDOIService) MCRConfiguration2.getInstanceOf(MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX + serviceID).get();
    try {
        MCRDataciteClient dataciteClient = registrationService.getDataciteClient();
        List<MCRDigitalObjectIdentifier> doiList = dataciteClient.getDOIList();
        doiList.stream().filter(doi -> {
            boolean isTestDOI = doi.getPrefix().equals(MCRDigitalObjectIdentifier.TEST_DOI_PREFIX);
            return !isTestDOI;
        }).forEach(doi -> {
            try {
                URI uri = dataciteClient.resolveDOI(doi);
                if (uri.toString().startsWith(registrationService.getRegisterURL())) {
                    LOGGER.info("Checking DOI: {}", doi.asString());
                    MCRObjectID objectID = getObjectID(uri);
                    if (MCRMetadataManager.exists(objectID)) {
                        if (!registrationService.isRegistered(objectID, "")) {
                            LOGGER.info("DOI is not registered in MyCoRe. Add to Database: {}", doi.asString());
                            MCRPI databaseEntry = new MCRPI(doi.asString(), registrationService.getType(), objectID.toString(), "", serviceID, new Date());
                            MCREntityManagerProvider.getCurrentEntityManager().persist(databaseEntry);
                        }
                        // Update main files
                        MCRObject obj = MCRMetadataManager.retrieveMCRObject(objectID);
                        List<Map.Entry<String, URI>> entryList = registrationService.getMediaList(obj);
                        dataciteClient.setMediaList(doi, entryList);
                    } else {
                        LOGGER.info("Could not find Object : {}", objectID);
                    }
                } else {
                    LOGGER.info("DOI/URL is not from this application: {}/{}", doi.asString(), uri);
                }
            } catch (MCRPersistentIdentifierException e) {
                LOGGER.error("Error occurred for DOI: {}", doi, e);
            }
        });
    } catch (MCRPersistentIdentifierException e) {
        LOGGER.error("Error while receiving DOI list from Registration-Service!", e);
    }
}
Also used : URL(java.net.URL) Date(java.util.Date) MCRContentTransformerFactory(org.mycore.common.content.transformer.MCRContentTransformerFactory) Document(org.jdom2.Document) MCRPI(org.mycore.pi.backend.MCRPI) JDOMSource(org.jdom2.transform.JDOMSource) MCRIdentifierUnresolvableException(org.mycore.pi.exceptions.MCRIdentifierUnresolvableException) MCRPIServiceManager(org.mycore.pi.MCRPIServiceManager) JDOMException(org.jdom2.JDOMException) Locale(java.util.Locale) Map(java.util.Map) MCRPIMetadataService(org.mycore.pi.MCRPIMetadataService) URI(java.net.URI) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRContent(org.mycore.common.content.MCRContent) Format(org.jdom2.output.Format) MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) MCRBaseContent(org.mycore.common.content.MCRBaseContent) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) MCRCrossrefUtil(org.mycore.pi.doi.crossref.MCRCrossrefUtil) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRDigitalObjectIdentifier(org.mycore.pi.doi.MCRDigitalObjectIdentifier) SAXException(org.xml.sax.SAXException) MCRActiveLinkException(org.mycore.datamodel.common.MCRActiveLinkException) Element(org.jdom2.Element) MCRDOIService(org.mycore.pi.doi.MCRDOIService) MCRDOIParser(org.mycore.pi.doi.MCRDOIParser) MCRConstants(org.mycore.common.MCRConstants) HashMap(java.util.HashMap) MCRException(org.mycore.common.MCRException) Schema(javax.xml.validation.Schema) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) MCRCommandGroup(org.mycore.frontend.cli.annotation.MCRCommandGroup) XMLConstants(javax.xml.XMLConstants) MCRAccessException(org.mycore.access.MCRAccessException) MCRDataciteClient(org.mycore.pi.doi.client.datacite.MCRDataciteClient) SchemaFactory(javax.xml.validation.SchemaFactory) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) IOException(java.io.IOException) XMLOutputter(org.jdom2.output.XMLOutputter) MCRContentTransformer(org.mycore.common.content.transformer.MCRContentTransformer) MCRObject(org.mycore.datamodel.metadata.MCRObject) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) MCRDOIService(org.mycore.pi.doi.MCRDOIService) MCRPI(org.mycore.pi.backend.MCRPI) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException) URI(java.net.URI) Date(java.util.Date) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRDigitalObjectIdentifier(org.mycore.pi.doi.MCRDigitalObjectIdentifier) MCRDataciteClient(org.mycore.pi.doi.client.datacite.MCRDataciteClient) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Aggregations

MCRConfiguration2 (org.mycore.common.config.MCRConfiguration2)12 Collectors (java.util.stream.Collectors)7 List (java.util.List)6 LogManager (org.apache.logging.log4j.LogManager)6 Logger (org.apache.logging.log4j.Logger)6 IOException (java.io.IOException)5 Element (org.jdom2.Element)5 MCRException (org.mycore.common.MCRException)5 Date (java.util.Date)4 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)4 ServletContext (jakarta.servlet.ServletContext)3 URI (java.net.URI)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Document (org.jdom2.Document)3 JDOMException (org.jdom2.JDOMException)3 Format (org.jdom2.output.Format)3 XMLOutputter (org.jdom2.output.XMLOutputter)3 MCRMetadataManager (org.mycore.datamodel.metadata.MCRMetadataManager)3