Search in sources :

Example 1 with DocumentType

use of io.openk9.plugin.driver.manager.api.DocumentType in project openk9 by smclab.

the class DocumentTypeProviderImpl method addDocumentTypeFactory.

@Reference(service = DocumentTypeFactory.class, bind = "addDocumentTypeFactory", unbind = "removeDocumentTypeFactory", policy = ReferencePolicy.STATIC, policyOption = ReferencePolicyOption.GREEDY, cardinality = ReferenceCardinality.MULTIPLE)
public void addDocumentTypeFactory(DocumentTypeFactory documentTypeFactory, Map<String, Object> props) {
    Object pluginDriverNameObj = props.get(DocumentTypeFactory.PLUGIN_DRIVER_NAME);
    if (pluginDriverNameObj == null) {
        _log.warn("DocumentTypeFactory must have " + DocumentTypeFactory.PLUGIN_DRIVER_NAME + " property. component: " + documentTypeFactory);
        return;
    }
    DocumentType newValue = documentTypeFactory.getDocumentType();
    if (Objects.isNull(newValue)) {
        _log.warn("DocumentType is null for DocumentTypeFactory: " + documentTypeFactory);
        return;
    }
    String pluginDriverName = (String) pluginDriverNameObj;
    Object defaultObj = props.get(DocumentTypeFactory.DEFAULT);
    boolean isDefault = defaultObj != null && (defaultObj instanceof String ? Boolean.parseBoolean((String) defaultObj) : (defaultObj instanceof Boolean ? (Boolean) defaultObj : false));
    if (isDefault) {
        DocumentType previousValue = _defaultDocumentTypeMap.put(pluginDriverName, newValue);
        _actionMap.put(documentTypeFactory, () -> _defaultDocumentTypeMap.remove(pluginDriverName));
        if (previousValue != null) {
            _log.warn("DocumentTypeFactory previous: " + previousValue + " new: " + newValue);
        }
    }
    List<DocumentType> documentTypes = _documentTypeMap.computeIfAbsent(pluginDriverName, s -> new CopyOnWriteArrayList<>());
    documentTypes.add(newValue);
    Action action = _actionMap.get(documentTypeFactory);
    Action newAction = () -> documentTypes.remove(newValue);
    if (action != null) {
        _actionMap.put(documentTypeFactory, () -> {
            action.exec();
            newAction.exec();
        });
    } else {
        _actionMap.put(documentTypeFactory, newAction);
    }
}
Also used : DocumentType(io.openk9.plugin.driver.manager.api.DocumentType) Reference(org.osgi.service.component.annotations.Reference)

Example 2 with DocumentType

use of io.openk9.plugin.driver.manager.api.DocumentType in project openk9 by smclab.

the class PluginDriverBundleTrackerCustomizer method addingBundle.

@Override
public Void addingBundle(Bundle bundle, BundleEvent event) {
    if (bundle.getState() != Bundle.ACTIVE) {
        removedBundle(bundle, event, null);
        return null;
    }
    Dictionary<String, String> headers = bundle.getHeaders(null);
    String pluginDriverConfiguration = headers.get(Constants.PLUGIN_DRIVER_CONFIGURATION);
    if (pluginDriverConfiguration == null) {
        pluginDriverConfiguration = "plugin-driver-config.json";
    }
    URL entry = bundle.getEntry(pluginDriverConfiguration);
    if (entry == null) {
        return null;
    }
    PluginDriverConfig pluginDriverConfig;
    try (InputStream is = entry.openStream()) {
        byte[] bytes = is.readAllBytes();
        pluginDriverConfig = _jsonFactory.fromJson(bytes, PluginDriverConfig.class);
    } catch (IOException e) {
        _log.error(e.getMessage(), e);
        return null;
    }
    String pluginDriverName = pluginDriverConfig.getName();
    String driverServiceName = pluginDriverConfig.getDriverServiceName() != null ? pluginDriverConfig.getDriverServiceName() : pluginDriverName;
    boolean schedulerEnabled = pluginDriverConfig.isSchedulerEnabled();
    PluginDriverConfig.Type type = pluginDriverConfig.getType();
    PluginDriver pluginDriver;
    switch(type) {
        case HTTP:
            {
                Map<String, Object> options = pluginDriverConfig.getOptions();
                if (options == null) {
                    options = Map.of();
                }
                String path = (String) options.getOrDefault("path", "");
                String url = (String) options.getOrDefault("url", "");
                Map<String, Object> headersObject = (Map<String, Object>) options.getOrDefault("headers", Map.of());
                String method = (String) options.getOrDefault("method", "GET");
                List<String> jsonKeys = (List<String>) options.getOrDefault("jsonKeys", new String[0]);
                int methodN = _findHttpMethod(method);
                HttpClient httpClient = _httpClientFactory.getHttpClient(url);
                pluginDriver = new BasePluginDriver() {

                    @Override
                    protected Map<String, Object> headersObject() {
                        return headersObject;
                    }

                    @Override
                    protected String[] headers() {
                        return new String[0];
                    }

                    @Override
                    protected String path() {
                        return path;
                    }

                    @Override
                    protected int method() {
                        return methodN;
                    }

                    @Override
                    protected String[] jsonKeys() {
                        return jsonKeys.toArray(new String[0]);
                    }

                    @Override
                    protected JsonFactory getJsonFactory() {
                        return _jsonFactory;
                    }

                    @Override
                    protected HttpClient getHttpClient() {
                        return httpClient;
                    }

                    @Override
                    public String getName() {
                        return pluginDriverName;
                    }

                    @Override
                    public boolean schedulerEnabled() {
                        return schedulerEnabled;
                    }

                    @Override
                    public String getDriverServiceName() {
                        return driverServiceName;
                    }
                };
                break;
            }
        default:
            throw new IllegalStateException("type: " + type + " not supported");
    }
    List<AutoCloseables.AutoCloseableSafe> autoCloseableList = new ArrayList<>();
    ServiceRegistration<PluginDriver> pluginDriverServiceRegistration = bundle.getBundleContext().registerService(PluginDriver.class, pluginDriver, null);
    autoCloseableList.add(AutoCloseables.mergeAutoCloseableToSafe(pluginDriverServiceRegistration::unregister));
    for (DocumentTypeConfig documentType : pluginDriverConfig.getDocumentTypes()) {
        DocumentTypeFactory.DefaultDocumentTypeFactory documentTypeFactory = DocumentTypeFactory.DefaultDocumentTypeFactory.of(pluginDriver.getName(), documentType.isDefaultDocumentType(), DocumentType.builder().icon(documentType.getIcon()).name(documentType.getName()).searchKeywords(_searchKeywordConfigToSearchKeyword(documentType.getSearchKeywords())).sourceFields(_mappingsToSourceFields(documentType.getMappings())).build());
        autoCloseableList.add(_documentTypeFactoryRegistry.register(documentTypeFactory));
    }
    for (EnrichProcessorConfig enrichProcessor : pluginDriverConfig.getEnrichProcessors()) {
        String name = enrichProcessor.getName();
        if (name == null || name.isBlank()) {
            _log.warn("name must be specified");
            continue;
        }
        EnrichProcessorConfig.Type typeEP = enrichProcessor.getType();
        if (typeEP == null) {
            _log.warn("name enrichProcessor.type be specified");
            continue;
        }
        Map<String, Object> options = enrichProcessor.getOptions();
        if (options == null) {
            options = Map.of();
        }
        EnrichProcessor enrichProcessorService = null;
        switch(typeEP) {
            case SYNC:
                Map<String, Object> headersEP = (Map<String, Object>) options.getOrDefault("headers", Map.of());
                String pathEP = (String) options.getOrDefault("path", "");
                String urlEP = (String) options.getOrDefault("url", "");
                String methodStringEP = (String) options.getOrDefault("method", "GET");
                int methodEP = _findHttpMethod(methodStringEP);
                BaseNerEnrichProcessor baseNerEnrichProcessor = new BaseNerEnrichProcessor() {

                    @Override
                    public String name() {
                        return name;
                    }

                    @Override
                    protected Map<String, Object> getHeaders() {
                        return headersEP;
                    }

                    @Override
                    protected int getMethod() {
                        return methodEP;
                    }

                    @Override
                    protected String getPath() {
                        return pathEP;
                    }
                };
                baseNerEnrichProcessor.setHttpClient(_httpClientFactory.getHttpClient(urlEP));
                baseNerEnrichProcessor.setJsonFactory(_jsonFactory);
                baseNerEnrichProcessor.setEntityManagerClient(_entityManagerClient);
                enrichProcessorService = baseNerEnrichProcessor;
                break;
            case ASYNC:
                String destinationName = (String) options.get("destinationName");
                if (destinationName == null || destinationName.isBlank()) {
                    _log.warn("destinationName must be specified");
                    break;
                }
                enrichProcessorService = new AsyncEnrichProcessor() {

                    @Override
                    public String destinationName() {
                        return destinationName;
                    }

                    @Override
                    public String name() {
                        return name;
                    }
                };
                break;
            default:
                throw new IllegalStateException("type: " + typeEP + " not supported");
        }
        if (enrichProcessorService != null) {
            ServiceRegistration<EnrichProcessor> enrichProcessorServiceRegistration = bundle.getBundleContext().registerService(EnrichProcessor.class, enrichProcessorService, null);
            autoCloseableList.add(AutoCloseables.mergeAutoCloseableToSafe(enrichProcessorServiceRegistration::unregister));
        }
    }
    _registrationMap.put(bundle, AutoCloseables.reduceAutoCloseableSafe(autoCloseableList));
    return null;
}
Also used : ArrayList(java.util.ArrayList) EnrichProcessorConfig(io.openk9.plugin.driver.manager.api.config.EnrichProcessorConfig) AsyncEnrichProcessor(io.openk9.search.enrich.api.AsyncEnrichProcessor) URL(java.net.URL) PluginDriverConfig(io.openk9.plugin.driver.manager.api.config.PluginDriverConfig) ArrayList(java.util.ArrayList) List(java.util.List) InputStream(java.io.InputStream) BaseNerEnrichProcessor(io.openk9.search.enrich.api.BaseNerEnrichProcessor) DocumentTypeConfig(io.openk9.plugin.driver.manager.api.config.DocumentTypeConfig) IOException(java.io.IOException) AsyncEnrichProcessor(io.openk9.search.enrich.api.AsyncEnrichProcessor) BaseNerEnrichProcessor(io.openk9.search.enrich.api.BaseNerEnrichProcessor) EnrichProcessor(io.openk9.search.enrich.api.EnrichProcessor) HttpClient(io.openk9.http.client.HttpClient) DocumentTypeFactory(io.openk9.plugin.driver.manager.api.DocumentTypeFactory) BasePluginDriver(io.openk9.plugin.driver.manager.api.BasePluginDriver) BasePluginDriver(io.openk9.plugin.driver.manager.api.BasePluginDriver) PluginDriver(io.openk9.plugin.driver.manager.api.PluginDriver) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 3 with DocumentType

use of io.openk9.plugin.driver.manager.api.DocumentType in project openk9 by smclab.

the class DocumentTypesEndpoint method _mapToResponse.

private Object _mapToResponse(List<Tuple2<Datasource, PluginDriverDTO>> list) {
    Map<String, Collection<String>> response = new HashMap<>();
    for (Tuple2<Datasource, PluginDriverDTO> t2 : list) {
        PluginDriverDTO pluginDriver = t2.getT2();
        for (DocumentTypeDTO documentType : pluginDriver.getDocumentTypes()) {
            String name = documentType.getName();
            List<SearchKeywordDTO> searchKeywords = documentType.getSearchKeywords();
            List<String> keywords = searchKeywords.stream().map(SearchKeywordDTO::getKeyword).collect(Collectors.toList());
            Collection<String> prevKeywords = response.get(name);
            Set<String> combine = new HashSet<>(keywords);
            if (prevKeywords != null) {
                combine.addAll(prevKeywords);
            }
            response.put(name, combine);
        }
    }
    return response;
}
Also used : Datasource(io.openk9.model.Datasource) HashMap(java.util.HashMap) SearchKeywordDTO(io.openk9.plugin.driver.manager.model.SearchKeywordDTO) Collection(java.util.Collection) DocumentTypeDTO(io.openk9.plugin.driver.manager.model.DocumentTypeDTO) PluginDriverDTO(io.openk9.plugin.driver.manager.model.PluginDriverDTO) HashSet(java.util.HashSet)

Example 4 with DocumentType

use of io.openk9.plugin.driver.manager.api.DocumentType in project openk9 by smclab.

the class EnrichPipelineProcessor method _adaptIngestionPayload.

private Tuple3<DatasourceContext, ObjectNode, PluginDriverDTO> _adaptIngestionPayload(DatasourceContext datasourceContext, ObjectNode ingestionPayload, PluginDriverDTO pluginDriverDTO) {
    ObjectNode newIngestionPayload = ingestionPayload;
    if (newIngestionPayload.hasNonNull(io.openk9.core.api.constant.Constants.DATASOURCE_PAYLOAD)) {
        JsonNode datasourcePayload = newIngestionPayload.remove(io.openk9.core.api.constant.Constants.DATASOURCE_PAYLOAD);
        if (datasourcePayload.isObject()) {
            ObjectNode jsonNodes = datasourcePayload.toObjectNode();
            for (Map.Entry<String, JsonNode> field : jsonNodes.fields()) {
                newIngestionPayload.set(field.getKey(), field.getValue());
            }
        }
    }
    if (!ingestionPayload.hasNonNull(Constants.DATASOURCE_NAME)) {
        newIngestionPayload = newIngestionPayload.deepCopy().put(Constants.DATASOURCE_NAME, pluginDriverDTO.getName());
    }
    if (ingestionPayload.hasNonNull(io.openk9.core.api.constant.Constants.TYPE) && !ingestionPayload.get(io.openk9.core.api.constant.Constants.TYPE).toArrayNode().isEmpty()) {
        return Tuples.of(datasourceContext, ingestionPayload, pluginDriverDTO);
    }
    DocumentTypeDTO documentType = pluginDriverDTO.getDefaultDocumentType();
    return Tuples.of(datasourceContext, newIngestionPayload.set(io.openk9.core.api.constant.Constants.TYPE, _jsonFactory.createArrayNode().add(documentType.getName())), pluginDriverDTO);
}
Also used : ObjectNode(io.openk9.json.api.ObjectNode) JsonNode(io.openk9.json.api.JsonNode) Map(java.util.Map) DocumentTypeDTO(io.openk9.plugin.driver.manager.model.DocumentTypeDTO)

Example 5 with DocumentType

use of io.openk9.plugin.driver.manager.api.DocumentType in project openk9 by smclab.

the class MappingsDocumentTypeFactoryCustomizer method apply.

@Override
public Mono<Void> apply(Map.Entry<String, List<DocumentType>> entry) {
    List<Field> collect = entry.getValue().stream().flatMap(documentType -> {
        List<Field> sourceFields = documentType.getSourceFields();
        if (sourceFields == null) {
            return Stream.empty();
        }
        if (sourceFields.size() == 1) {
            Field field = sourceFields.get(0);
            if (field instanceof Field.FieldMappings) {
                return Stream.of(field);
            }
        }
        return sourceFields.stream().map(child -> Field.of(documentType.getName(), child));
    }).collect(Collectors.toList());
    if (collect.stream().allMatch(f -> f instanceof Field.FieldMappings)) {
        Map<String, Object> accumulator = new HashMap<>();
        for (Field field : collect) {
            deepMerge(accumulator, field.getExtra());
        }
        String pluginDriverName = entry.getKey();
        return _indexWriterEventPublisher.publishCreateIndexTemplate(IndexTemplateDTO.of(pluginDriverName + "_template", null, List.of("*-" + pluginDriverName + "-data"), _jsonFactory.toJson(accumulator), List.of("data"), 10));
    }
    Map<String, Object> objectNode = new HashMap<>();
    for (Field parent : collect) {
        Map<String, Object> fieldNode = _createFieldNode(parent);
        Map<String, Object> parentNodeWithName = fieldNode;
        Field child = parent.getChild();
        while (child != Field.FieldObj.NIL) {
            Map<String, Object> parentNode = (Map<String, Object>) parentNodeWithName.get(parent.getName());
            Map<String, Object> childNode = _createFieldNode(child);
            parentNode.put("properties", childNode);
            parentNodeWithName = childNode;
            parent = child;
            child = child.getChild();
        }
        objectNode = _merge(objectNode, fieldNode);
    }
    String pluginDriverName = entry.getKey();
    return _indexWriterEventPublisher.publishCreateIndexTemplate(IndexTemplateDTO.of(pluginDriverName + "_template", null, List.of("*-" + pluginDriverName + "-data"), _jsonFactory.toJson(Map.of("properties", objectNode)), List.of("data"), 10));
}
Also used : Field(io.openk9.plugin.driver.manager.api.Field) FieldType(io.openk9.plugin.driver.manager.api.FieldType) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Mono(reactor.core.publisher.Mono) HashMap(java.util.HashMap) IndexTemplateDTO(io.openk9.index.writer.model.IndexTemplateDTO) DocumentType(io.openk9.plugin.driver.manager.api.DocumentType) Collectors(java.util.stream.Collectors) JsonFactory(io.openk9.json.api.JsonFactory) DocumentTypeFactoryCustomizer(io.openk9.plugin.driver.manager.api.DocumentTypeFactoryCustomizer) Component(org.osgi.service.component.annotations.Component) List(java.util.List) Stream(java.util.stream.Stream) Map(java.util.Map) IndexWriterEventPublisher(io.openk9.index.writer.mappings.publisher.api.IndexWriterEventPublisher) Reference(org.osgi.service.component.annotations.Reference) Field(io.openk9.plugin.driver.manager.api.Field) HashMap(java.util.HashMap) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

DocumentType (io.openk9.plugin.driver.manager.api.DocumentType)3 DocumentTypeDTO (io.openk9.plugin.driver.manager.model.DocumentTypeDTO)3 List (java.util.List)3 Map (java.util.Map)3 Reference (org.osgi.service.component.annotations.Reference)3 PluginDriver (io.openk9.plugin.driver.manager.api.PluginDriver)2 PluginDriverDTO (io.openk9.plugin.driver.manager.model.PluginDriverDTO)2 SearchKeywordDTO (io.openk9.plugin.driver.manager.model.SearchKeywordDTO)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 Collectors (java.util.stream.Collectors)2 Component (org.osgi.service.component.annotations.Component)2 HttpClient (io.openk9.http.client.HttpClient)1 IndexWriterEventPublisher (io.openk9.index.writer.mappings.publisher.api.IndexWriterEventPublisher)1 IndexTemplateDTO (io.openk9.index.writer.model.IndexTemplateDTO)1 JsonFactory (io.openk9.json.api.JsonFactory)1 JsonNode (io.openk9.json.api.JsonNode)1 ObjectNode (io.openk9.json.api.ObjectNode)1 Datasource (io.openk9.model.Datasource)1 BasePluginDriver (io.openk9.plugin.driver.manager.api.BasePluginDriver)1