Search in sources :

Example 1 with Payload

use of io.openk9.entity.manager.dto.Payload in project openk9 by smclab.

the class GetOrAddEntitiesConsumer method apply.

public Mono<ObjectNode> apply(ObjectNode objectNode) {
    return Mono.defer(() -> {
        ObjectNode datasourceContextJson = objectNode.get("datasourceContext").toObjectNode();
        long datasourceId = datasourceContextJson.get("datasource").get("datasourceId").asLong();
        long tenantId = datasourceContextJson.get("tenant").get("tenantId").asLong();
        JsonNode entities = objectNode.remove("entities");
        Mono<ArrayNode> entitiesField;
        if (entities.size() == 0) {
            entitiesField = Mono.just(_jsonFactory.createArrayNode());
        } else {
            ObjectNode responseJson = _jsonFactory.createObjectNode();
            responseJson.put("entities", entities);
            responseJson.put("tenantId", tenantId);
            responseJson.put("datasourceId", datasourceId);
            Request request = _jsonFactory.fromJson(responseJson.toString(), Request.class);
            List<RequestContext> requestContextList = request.getEntities().stream().map(entityRequest -> RequestContext.builder().current(entityRequest).tenantId(request.getTenantId()).datasourceId(request.getDatasourceId()).rest(request.getEntities().stream().filter(er -> er != entityRequest).collect(Collectors.toList())).build()).collect(Collectors.toList());
            Mono<List<EntityContext>> disambiguateListMono = GetOrAddEntities.stopWatch("disambiguate-all-entities", Flux.fromIterable(requestContextList).flatMap(requestContext -> GetOrAddEntities.stopWatch("disambiguate-" + requestContext.getCurrent().getName(), Mono.<EntityContext>create(fluxSink -> _startDisambiguation.disambiguate(requestContext, fluxSink)))).collectList());
            Mono<ResponseList> writeRelations = disambiguateListMono.flatMap(entityContexts -> GetOrAddEntities.stopWatch("write-relations", writeRelations(entityContexts)));
            Mono<ResponseList> responseListWrapper = _transactional ? _graphClient.makeTransactional(writeRelations) : writeRelations;
            entitiesField = responseListWrapper.map(responseListDTO -> {
                List<Response> responseList = responseListDTO.getResponse();
                ArrayNode entitiesArrayNode = entities.toArrayNode();
                ArrayNode arrayNode = _jsonFactory.createArrayNode();
                for (JsonNode node : entitiesArrayNode) {
                    Optional<Response> responseOptional = responseList.stream().filter(response -> node.get("tmpId").asLong() == response.getTmpId()).findFirst();
                    if (responseOptional.isPresent()) {
                        Entity entity = responseOptional.get().getEntity();
                        ObjectNode result = _jsonFactory.createObjectNode();
                        result.put("entityType", entity.getType());
                        result.put("id", entity.getId());
                        result.put("context", node.get("context"));
                        arrayNode.add(result);
                    }
                }
                return arrayNode;
            });
        }
        return entitiesField.map(entitiesArray -> {
            ObjectNode payload = objectNode.get("payload").toObjectNode();
            payload.set("entities", entitiesArray);
            return objectNode;
        }).timeout(Duration.ofSeconds(_timeout), Mono.error(new TimeoutException("timeout on entities count: " + entities.size() + " (Did not observe any item or terminal signal within " + Duration.ofSeconds(_timeout).toMillis() + "ms)")));
    });
}
Also used : Response(io.openk9.entity.manager.model.payload.Response) SenderReactor(io.openk9.ingestion.api.SenderReactor) Disposable(reactor.core.Disposable) JsonNode(io.openk9.json.api.JsonNode) LoggerFactory(org.slf4j.LoggerFactory) Tuples(reactor.util.function.Tuples) Tuple2(reactor.util.function.Tuple2) TimeoutException(java.util.concurrent.TimeoutException) EntityRequest(io.openk9.entity.manager.model.payload.EntityRequest) GraphClient(io.openk9.relationship.graph.api.client.GraphClient) ArrayNode(io.openk9.json.api.ArrayNode) JsonFactory(io.openk9.json.api.JsonFactory) ArrayList(java.util.ArrayList) Component(org.osgi.service.component.annotations.Component) Statement(org.neo4j.cypherdsl.core.Statement) Duration(java.time.Duration) OutboundMessageFactory(io.openk9.ingestion.api.OutboundMessageFactory) Schedulers(reactor.core.scheduler.Schedulers) Request(io.openk9.entity.manager.model.payload.Request) Cypher(org.neo4j.cypherdsl.core.Cypher) Activate(org.osgi.service.component.annotations.Activate) Node(org.neo4j.cypherdsl.core.Node) Binding(io.openk9.ingestion.api.Binding) Logger(org.slf4j.Logger) Deactivate(org.osgi.service.component.annotations.Deactivate) Functions(org.neo4j.cypherdsl.core.Functions) RelationRequest(io.openk9.entity.manager.model.payload.RelationRequest) Mono(reactor.core.publisher.Mono) Entity(io.openk9.entity.manager.model.Entity) Collectors(java.util.stream.Collectors) Flux(reactor.core.publisher.Flux) List(java.util.List) Stream(java.util.stream.Stream) ResponseList(io.openk9.entity.manager.model.payload.ResponseList) ReceiverReactor(io.openk9.ingestion.api.ReceiverReactor) Modified(org.osgi.service.component.annotations.Modified) Optional(java.util.Optional) ObjectNode(io.openk9.json.api.ObjectNode) Reference(org.osgi.service.component.annotations.Reference) Cypher.literalOf(org.neo4j.cypherdsl.core.Cypher.literalOf) Entity(io.openk9.entity.manager.model.Entity) ObjectNode(io.openk9.json.api.ObjectNode) Optional(java.util.Optional) EntityRequest(io.openk9.entity.manager.model.payload.EntityRequest) Request(io.openk9.entity.manager.model.payload.Request) RelationRequest(io.openk9.entity.manager.model.payload.RelationRequest) JsonNode(io.openk9.json.api.JsonNode) ResponseList(io.openk9.entity.manager.model.payload.ResponseList) ArrayList(java.util.ArrayList) List(java.util.List) ResponseList(io.openk9.entity.manager.model.payload.ResponseList) ArrayNode(io.openk9.json.api.ArrayNode) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with Payload

use of io.openk9.entity.manager.dto.Payload in project openk9 by smclab.

the class EntityManagerBus method run.

@SneakyThrows
public void run() {
    while (true) {
        Payload request = _entityManagerQueue.take();
        TransactionContext transactionContext = _hazelcastInstance.newTransactionContext();
        transactionContext.beginTransaction();
        try {
            TransactionalMap<EntityKey, Entity> entityTransactionalMap = transactionContext.getMap("entityMap");
            TransactionalMap<EntityRelationKey, EntityRelation> transactionalEntityRelationMap = transactionContext.getMap("entityRelationMap");
            TransactionalMultiMap<DocumentKey, String> documentEntityMap = transactionContext.getMultiMap("documentEntityMap");
            EntityManagerRequest payload = request.getPayload();
            _loggerAggregator.emitLog("process ingestionId", payload.getIngestionId());
            long tenantId = payload.getTenantId();
            String ingestionId = payload.getIngestionId();
            List<EntityRequest> entities = request.getEntities();
            Map<EntityKey, Entity> localEntityMap = new HashMap<>(entities.size());
            for (EntityRequest entityRequest : entities) {
                String name = entityRequest.getName();
                String type = entityRequest.getType();
                String cacheId = Long.toString(_entityFlakeId.newId());
                EntityKey key = EntityKey.of(tenantId, name, type, cacheId, ingestionId);
                Entity entity = new Entity(null, cacheId, tenantId, name, type, null, ingestionId, false, true, entityRequest.getContext());
                entityTransactionalMap.set(key, entity);
                localEntityMap.put(key, entity);
                for (EntityRequest entityRequest2 : entities) {
                    for (RelationRequest relation : entityRequest2.getRelations()) {
                        if (relation.getTo().equals(entityRequest.getTmpId())) {
                            relation.setTo(entity.getCacheId());
                        }
                    }
                }
            }
            for (EntityRequest entity : entities) {
                List<RelationRequest> relations = entity.getRelations();
                if (relations == null || relations.isEmpty()) {
                    continue;
                }
                Collection<Entity> values = localEntityMap.values();
                Entity current = values.stream().filter(e -> e.getName().equals(entity.getName()) && e.getType().equals(entity.getType())).findFirst().orElse(null);
                if (current == null) {
                    continue;
                }
                for (RelationRequest relation : relations) {
                    String to = relation.getTo();
                    String name = relation.getName();
                    for (Entity value : values) {
                        if (value.getCacheId().equals(to)) {
                            long entityRelationId = _entityRelationFlakeId.newId();
                            EntityRelation entityRelation = new EntityRelation(entityRelationId, current.getCacheId(), ingestionId, name, value.getCacheId());
                            transactionalEntityRelationMap.set(EntityRelationKey.of(entityRelationId, current.getCacheId(), ingestionId), entityRelation);
                        }
                    }
                }
            }
            if (!localEntityMap.isEmpty()) {
                DocumentKey key = DocumentKey.of(payload.getDatasourceId(), payload.getContentId(), tenantId);
                for (Entity value : localEntityMap.values()) {
                    documentEntityMap.put(key, value.getCacheId());
                }
            }
        } catch (Exception e) {
            _log.error(e.getMessage(), e);
            transactionContext.rollbackTransaction();
        } finally {
            transactionContext.commitTransaction();
        }
    }
}
Also used : Entity(io.openk9.entity.manager.cache.model.Entity) HashMap(java.util.HashMap) RelationRequest(io.openk9.entity.manager.dto.RelationRequest) EntityRelationKey(io.openk9.entity.manager.cache.model.EntityRelationKey) EntityKey(io.openk9.entity.manager.cache.model.EntityKey) EntityRelation(io.openk9.entity.manager.cache.model.EntityRelation) EntityRequest(io.openk9.entity.manager.dto.EntityRequest) TransactionContext(com.hazelcast.transaction.TransactionContext) DocumentKey(io.openk9.entity.manager.cache.model.DocumentKey) Payload(io.openk9.entity.manager.dto.Payload) EntityManagerRequest(io.openk9.entity.manager.dto.EntityManagerRequest) SneakyThrows(lombok.SneakyThrows)

Example 3 with Payload

use of io.openk9.entity.manager.dto.Payload in project openk9 by smclab.

the class EntityManagerConsumer method consume.

@Incoming("entity-manager-request")
@Outgoing("entity-manager-response")
@Blocking
public Message<JsonObject> consume(Object obj) throws InterruptedException {
    JsonObject jsonObject = obj instanceof JsonObject ? (JsonObject) obj : new JsonObject(new String((byte[]) obj));
    Payload payload = jsonObject.mapTo(Payload.class);
    _entityManagerQueue.offer(payload, 45, TimeUnit.SECONDS);
    String replyTo = payload.getReplyTo();
    return Message.of(jsonObject, Metadata.of(new OutgoingRabbitMQMetadata.Builder().withRoutingKey(replyTo).withTimestamp(ZonedDateTime.now()).build()));
}
Also used : OutgoingRabbitMQMetadata(io.smallrye.reactive.messaging.rabbitmq.OutgoingRabbitMQMetadata) JsonObject(io.vertx.core.json.JsonObject) Payload(io.openk9.entity.manager.dto.Payload) Incoming(org.eclipse.microprofile.reactive.messaging.Incoming) Blocking(io.smallrye.reactive.messaging.annotations.Blocking) Outgoing(org.eclipse.microprofile.reactive.messaging.Outgoing)

Example 4 with Payload

use of io.openk9.entity.manager.dto.Payload in project openk9 by smclab.

the class InsertIndexWriter method _createDocWriterRequest.

private Mono<DocWriteRequest> _createDocWriterRequest(String indexName, ObjectNode enrichProcessorContext) {
    return Mono.defer(() -> {
        ObjectNode objectNode = enrichProcessorContext.get("payload").toObjectNode();
        String contentId = objectNode.get("contentId").asText();
        return _search.search(factory -> {
            SearchRequest searchRequest = new SearchRequest(indexName);
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("contentId", contentId);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(matchQueryBuilder);
            return searchRequest.source(searchSourceBuilder);
        }).onErrorReturn(SearchUtil.EMPTY_SEARCH_RESPONSE).filter(e -> e.getHits().getHits().length > 0).flatMapIterable(SearchResponse::getHits).next().map(e -> new UpdateRequest(indexName, e.getId()).doc(objectNode.toString(), XContentType.JSON)).cast(DocWriteRequest.class).switchIfEmpty(Mono.fromSupplier(() -> new IndexRequest(indexName).source(objectNode.toString(), XContentType.JSON)));
    });
}
Also used : MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder) Logger(org.slf4j.Logger) Disposable(reactor.core.Disposable) SearchUtil(io.openk9.search.client.api.util.SearchUtil) XContentType(org.elasticsearch.common.xcontent.XContentType) IndexBus(io.openk9.search.client.api.IndexBus) Deactivate(org.osgi.service.component.annotations.Deactivate) LoggerFactory(org.slf4j.LoggerFactory) Search(io.openk9.search.client.api.Search) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) Mono(reactor.core.publisher.Mono) SearchRequest(org.elasticsearch.action.search.SearchRequest) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) JsonFactory(io.openk9.json.api.JsonFactory) IndexRequest(org.elasticsearch.action.index.IndexRequest) Component(org.osgi.service.component.annotations.Component) ReceiverReactor(io.openk9.ingestion.api.ReceiverReactor) SearchResponse(org.elasticsearch.action.search.SearchResponse) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) ObjectNode(io.openk9.json.api.ObjectNode) Activate(org.osgi.service.component.annotations.Activate) Reference(org.osgi.service.component.annotations.Reference) Binding(io.openk9.ingestion.api.Binding) SearchRequest(org.elasticsearch.action.search.SearchRequest) ObjectNode(io.openk9.json.api.ObjectNode) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 5 with Payload

use of io.openk9.entity.manager.dto.Payload in project openk9 by smclab.

the class EnrichPipelineProcessor method _mapToEnrichProcessorContext.

private ObjectNode _mapToEnrichProcessorContext(Tuple3<DatasourceContext, ObjectNode, PluginDriverDTO> t3) {
    List<String> dependencies = t3.getT1().getEnrichItems().stream().map(EnrichItem::getServiceName).collect(Collectors.toList());
    ObjectNode objectNode = _jsonFactory.createObjectNode();
    objectNode.put("pluginDriver", _jsonFactory.fromObjectToJsonNode(t3.getT3()));
    objectNode.put("dependencies", _jsonFactory.fromObjectToJsonNode(dependencies));
    objectNode.put("datasourceContext", _jsonFactory.fromObjectToJsonNode(t3.getT1()));
    objectNode.put("payload", t3.getT2());
    return objectNode;
}
Also used : ObjectNode(io.openk9.json.api.ObjectNode)

Aggregations

ObjectNode (io.openk9.json.api.ObjectNode)3 Payload (io.openk9.entity.manager.dto.Payload)2 Binding (io.openk9.ingestion.api.Binding)2 ReceiverReactor (io.openk9.ingestion.api.ReceiverReactor)2 JsonFactory (io.openk9.json.api.JsonFactory)2 Activate (org.osgi.service.component.annotations.Activate)2 TransactionContext (com.hazelcast.transaction.TransactionContext)1 DocumentKey (io.openk9.entity.manager.cache.model.DocumentKey)1 Entity (io.openk9.entity.manager.cache.model.Entity)1 EntityKey (io.openk9.entity.manager.cache.model.EntityKey)1 EntityRelation (io.openk9.entity.manager.cache.model.EntityRelation)1 EntityRelationKey (io.openk9.entity.manager.cache.model.EntityRelationKey)1 EntityManagerRequest (io.openk9.entity.manager.dto.EntityManagerRequest)1 EntityRequest (io.openk9.entity.manager.dto.EntityRequest)1 RelationRequest (io.openk9.entity.manager.dto.RelationRequest)1 Entity (io.openk9.entity.manager.model.Entity)1 EntityRequest (io.openk9.entity.manager.model.payload.EntityRequest)1 RelationRequest (io.openk9.entity.manager.model.payload.RelationRequest)1 Request (io.openk9.entity.manager.model.payload.Request)1 Response (io.openk9.entity.manager.model.payload.Response)1