示例#1
0
 private StreamingPropertyValue getStreamingPropertyValue(Vertex artifactVertex, String type) {
   StreamingPropertyValue mediaPropertyValue;
   if (MediaLumifyProperties.MIME_TYPE_AUDIO_MP4.equals(type)) {
     mediaPropertyValue = MediaLumifyProperties.AUDIO_MP4.getPropertyValue(artifactVertex);
     checkNotNull(
         mediaPropertyValue,
         String.format(
             "Could not find %s property on artifact %s",
             MediaLumifyProperties.AUDIO_MP4, artifactVertex.getId()));
   } else if (MediaLumifyProperties.MIME_TYPE_AUDIO_OGG.equals(type)) {
     mediaPropertyValue = MediaLumifyProperties.AUDIO_OGG.getPropertyValue(artifactVertex);
     checkNotNull(
         mediaPropertyValue,
         String.format(
             "Could not find %s property on artifact %s",
             MediaLumifyProperties.AUDIO_OGG, artifactVertex.getId()));
   } else if (MediaLumifyProperties.MIME_TYPE_VIDEO_MP4.equals(type)) {
     mediaPropertyValue = MediaLumifyProperties.VIDEO_MP4.getPropertyValue(artifactVertex);
     checkNotNull(
         mediaPropertyValue,
         String.format(
             "Could not find %s property on artifact %s",
             MediaLumifyProperties.VIDEO_MP4, artifactVertex.getId()));
   } else if (MediaLumifyProperties.MIME_TYPE_VIDEO_WEBM.equals(type)) {
     mediaPropertyValue = MediaLumifyProperties.VIDEO_WEBM.getPropertyValue(artifactVertex);
     checkNotNull(
         mediaPropertyValue,
         String.format(
             "Could not find %s property on artifact %s",
             MediaLumifyProperties.VIDEO_WEBM, artifactVertex.getId()));
   } else {
     throw new RuntimeException("Invalid video type: " + type);
   }
   return mediaPropertyValue;
 }
  private void saveVertexRelationships(
      List<VertexRelationship> vertexRelationships,
      List<TermMentionWithGraphVertex> termMentionsWithGraphVertices) {
    for (VertexRelationship vertexRelationship : vertexRelationships) {
      TermMentionWithGraphVertex sourceTermMentionsWithGraphVertex =
          findTermMentionWithGraphVertex(
              termMentionsWithGraphVertices, vertexRelationship.getSource());
      checkNotNull(sourceTermMentionsWithGraphVertex, "Could not find source");
      checkNotNull(sourceTermMentionsWithGraphVertex.getVertex(), "Could not find source vertex");

      Vertex targetVertex = graph.getVertex(vertexRelationship.getTargetId(), getAuthorizations());
      checkNotNull(sourceTermMentionsWithGraphVertex, "Could not find target vertex");

      String label = vertexRelationship.getLabel();
      checkNotNull(label, "label is required");

      Edge edge =
          trySingle(
              sourceTermMentionsWithGraphVertex
                  .getVertex()
                  .getEdges(targetVertex, Direction.OUT, label, getAuthorizations()));
      if (edge == null) {
        LOGGER.debug(
            "adding edge %s -> %s (%s)",
            sourceTermMentionsWithGraphVertex.getVertex().getId(), targetVertex.getId(), label);
        graph.addEdge(
            sourceTermMentionsWithGraphVertex.getVertex(),
            targetVertex,
            label,
            vertexRelationship.getVisibility(),
            getAuthorizations());
      }
    }
  }
示例#3
0
  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain)
      throws Exception {
    final String graphVertexId = getAttributeString(request, "graphVertexId");
    final String visibilitySource = getRequiredParameter(request, "visibilitySource");

    User user = getUser(request);
    Authorizations authorizations = getAuthorizations(request, user);
    String workspaceId = getActiveWorkspaceId(request);

    Vertex graphVertex = graph.getVertex(graphVertexId, authorizations);
    if (graphVertex == null) {
      respondWithNotFound(response);
      return;
    }

    if (!graph.isVisibilityValid(new Visibility(visibilitySource), authorizations)) {
      LOGGER.warn(
          "%s is not a valid visibility for %s user", visibilitySource, user.getDisplayName());
      respondWithBadRequest(response, "visibilitySource", getString(request, "visibility.invalid"));
      chain.next(request, response);
      return;
    }
    LOGGER.info(
        "changing vertex (%s) visibility source to %s",
        graphVertex.getId().toString(), visibilitySource);

    GraphUtil.VisibilityAndElementMutation<Vertex> setPropertyResult =
        GraphUtil.updateElementVisibilitySource(
            visibilityTranslator,
            graphVertex,
            GraphUtil.getSandboxStatus(graphVertex, workspaceId),
            visibilitySource,
            workspaceId,
            authorizations);
    auditRepository.auditVertexElementMutation(
        AuditAction.UPDATE,
        setPropertyResult.elementMutation,
        graphVertex,
        "",
        user,
        setPropertyResult.visibility.getVisibility());

    this.graph.flush();

    this.workQueueRepository.pushGraphPropertyQueue(
        graphVertex,
        null,
        LumifyVisibilityProperties.VISIBILITY_JSON_PROPERTY.getPropertyName(),
        workspaceId,
        visibilitySource);

    JSONObject json = JsonSerializer.toJson(graphVertex, workspaceId, authorizations);
    respondWithJson(response, json);
  }
示例#4
0
  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain)
      throws Exception {
    boolean download = getOptionalParameter(request, "download") != null;
    boolean playback = getOptionalParameter(request, "playback") != null;

    User user = getUser(request);
    Authorizations authorizations = getAuthorizations(request, user);

    String graphVertexId = UrlUtils.urlDecode(getAttributeString(request, "graphVertexId"));

    Vertex artifactVertex = graph.getVertex(graphVertexId, authorizations);
    if (artifactVertex == null) {
      respondWithNotFound(response);
      return;
    }

    String fileName = LumifyProperties.FILE_NAME.getPropertyValue(artifactVertex);
    if (fileName == null) {
      fileName = LumifyProperties.TITLE.getPropertyValue(artifactVertex);
    }

    if (playback) {
      handlePartialPlayback(request, response, artifactVertex, fileName, user);
    } else {
      String mimeType = getMimeType(artifactVertex);
      response.setContentType(mimeType);
      setMaxAge(response, EXPIRES_1_HOUR);
      if (download) {
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
      } else {
        response.addHeader("Content-Disposition", "inline; filename=" + fileName);
      }

      StreamingPropertyValue rawValue = LumifyProperties.RAW.getPropertyValue(artifactVertex);
      if (rawValue == null) {
        LOGGER.warn("Could not find raw on artifact: %s", artifactVertex.getId().toString());
        respondWithNotFound(response);
        return;
      }
      InputStream in = rawValue.getInputStream();
      try {
        IOUtils.copy(in, response.getOutputStream());
      } finally {
        in.close();
      }
    }

    chain.next(request, response);
  }
示例#5
0
  protected List<TermMentionWithGraphVertex> saveTermMentions(
      Vertex artifactGraphVertex,
      Iterable<TermMention> termMentions,
      String workspaceId,
      String visibilitySource) {
    getAuditRepository()
        .auditAnalyzedBy(
            AuditAction.ANALYZED_BY,
            artifactGraphVertex,
            getClass().getSimpleName(),
            getUser(),
            artifactGraphVertex.getVisibility());
    for (TermMentionFilter termMentionFilter : this.workerPrepareData.getTermMentionFilters()) {
      try {
        termMentions = termMentionFilter.apply(artifactGraphVertex, termMentions);
      } catch (Exception ex) {
        throw new LumifyException(
            "Failed to run term mention filter: " + termMentionFilter.getClass().getName(), ex);
      }
    }

    List<TermMentionWithGraphVertex> results = new ArrayList<TermMentionWithGraphVertex>();
    for (TermMention termMention : termMentions) {
      results.add(saveTermMention(artifactGraphVertex, termMention, workspaceId, visibilitySource));
    }
    return results;
  }
示例#6
0
  private void safeMap(LongWritable filePosition, Text line, Context context)
      throws IOException, InterruptedException {
    String lineString = line.toString();
    int colonOffet = lineString.indexOf(':');
    if (colonOffet < 1) {
      return;
    }
    long userId = Long.parseLong(lineString.substring(0, colonOffet));
    context.setStatus("User: "******"Friendster MR", "", user, visibility);
    context.write(key, AccumuloSession.createMutationFromRow(audit));

    String friends = lineString.substring(colonOffet + 1).trim();
    if ("notfound".equals(friends) || "private".equals(friends)) {
      // do nothing?
    } else {
      String[] friendsArray = friends.split(",");
      for (String friend : friendsArray) {
        friend = friend.trim();
        if (friend.length() == 0) {
          continue;
        }
        long friendId = Long.parseLong(friend);
        Vertex friendVertex = createUserVertex(friendId);
        addEdge(
            ImportMR.getFriendEdgeId(userVertex, friendVertex),
            userVertex,
            friendVertex,
            FriendsterOntology.EDGE_LABEL_FRIEND,
            visibility,
            authorizations);
        context.getCounter(FriendsterImportCounters.FRIEND_EDGES_CREATED).increment(1);
      }
    }

    context.getCounter(FriendsterImportCounters.USERS_PROCESSED).increment(1);
  }
  @Override
  public void execute(InputStream in, GraphPropertyWorkData data) throws Exception {
    LOGGER.debug("Extracting pattern [%s] from provided text", pattern);

    final String text = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));

    final Matcher matcher = pattern.matcher(text);

    List<TermMention> termMentions = new ArrayList<TermMention>();
    while (matcher.find()) {
      TermMention termMention =
          createTerm(matcher, data.getProperty().getKey(), data.getVisibility());
      termMentions.add(termMention);
    }
    Vertex v = (Vertex) data.getElement();
    getAuditRepository()
        .auditAnalyzedBy(
            AuditAction.ANALYZED_BY, v, getClass().getSimpleName(), getUser(), v.getVisibility());
    saveTermMentions((Vertex) data.getElement(), termMentions);
  }
示例#8
0
  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain)
      throws Exception {
    final String artifactId = getRequiredParameter(request, "artifactId");
    final String propertyKey = getRequiredParameter(request, "propertyKey");
    final long mentionStart = getRequiredParameterAsLong(request, "mentionStart");
    final long mentionEnd = getRequiredParameterAsLong(request, "mentionEnd");
    final String title = getRequiredParameter(request, "sign");
    final String conceptId = getRequiredParameter(request, "conceptId");
    final String visibilitySource = getRequiredParameter(request, "visibilitySource");
    final String resolvedVertexId = getOptionalParameter(request, "resolvedVertexId");
    final String justificationText = getOptionalParameter(request, "justificationText");
    final String sourceInfo = getOptionalParameter(request, "sourceInfo");
    String termMentionRowKeyString = getOptionalParameter(request, "rowKey");

    User user = getUser(request);
    String workspaceId = getActiveWorkspaceId(request);
    Workspace workspace = workspaceRepository.findById(workspaceId, user);

    Authorizations authorizations = getAuthorizations(request, user);

    JSONObject visibilityJson =
        GraphUtil.updateVisibilitySourceAndAddWorkspaceId(null, visibilitySource, workspaceId);
    LumifyVisibility visibility = this.visibilityTranslator.toVisibility(visibilityJson);
    if (!graph.isVisibilityValid(visibility.getVisibility(), authorizations)) {
      LOGGER.warn(
          "%s is not a valid visibility for %s user", visibilitySource, user.getDisplayName());
      respondWithBadRequest(response, "visibilitySource", STRINGS.getString("visibility.invalid"));
      chain.next(request, response);
      return;
    }

    Object id = resolvedVertexId == null ? graph.getIdGenerator().nextId() : resolvedVertexId;

    Concept concept = ontologyRepository.getConceptByIRI(conceptId);

    final Vertex artifactVertex = graph.getVertex(artifactId, authorizations);
    LumifyVisibility lumifyVisibility = visibilityTranslator.toVisibility(visibilityJson);
    Map<String, Object> metadata = new HashMap<String, Object>();
    LumifyVisibilityProperties.VISIBILITY_JSON_PROPERTY.setMetadata(metadata, visibilityJson);
    ElementMutation<Vertex> vertexMutation;
    Vertex vertex;
    if (resolvedVertexId != null) {
      vertex = graph.getVertex(id, authorizations);
      vertexMutation = vertex.prepareMutation();
    } else {
      vertexMutation = graph.prepareVertex(id, lumifyVisibility.getVisibility());
      GraphUtil.addJustificationToMutation(
          vertexMutation, justificationText, sourceInfo, lumifyVisibility);

      CONCEPT_TYPE.setProperty(
          vertexMutation, conceptId, metadata, lumifyVisibility.getVisibility());
      TITLE.addPropertyValue(
          vertexMutation, MULTI_VALUE_KEY, title, metadata, lumifyVisibility.getVisibility());

      vertex = vertexMutation.save(authorizations);

      auditRepository.auditVertexElementMutation(
          AuditAction.UPDATE, vertexMutation, vertex, "", user, lumifyVisibility.getVisibility());

      LumifyVisibilityProperties.VISIBILITY_JSON_PROPERTY.setProperty(
          vertexMutation, visibilityJson, metadata, lumifyVisibility.getVisibility());

      this.graph.flush();

      workspaceRepository.updateEntityOnWorkspace(
          workspace, vertex.getId(), false, null, null, user);
    }

    // TODO: a better way to check if the same edge exists instead of looking it up every time?
    Edge edge =
        graph.addEdge(
            artifactVertex,
            vertex,
            this.artifactHasEntityIri,
            lumifyVisibility.getVisibility(),
            authorizations);
    LumifyVisibilityProperties.VISIBILITY_JSON_PROPERTY.setProperty(
        edge, visibilityJson, metadata, lumifyVisibility.getVisibility(), authorizations);

    auditRepository.auditRelationship(
        AuditAction.CREATE,
        artifactVertex,
        vertex,
        edge,
        "",
        "",
        user,
        lumifyVisibility.getVisibility());

    TermMentionRowKey termMentionRowKey;
    if (termMentionRowKeyString != null) {
      termMentionRowKey = new TermMentionRowKey(RowKeyHelper.jsonDecode(termMentionRowKeyString));
    } else {
      termMentionRowKey =
          new TermMentionRowKey(
              artifactId, propertyKey, mentionStart, mentionEnd, edge.getId().toString());
    }
    TermMentionModel termMention = new TermMentionModel(termMentionRowKey);
    termMention
        .getMetadata()
        .setSign(title, lumifyVisibility.getVisibility())
        .setOntologyClassUri(concept.getDisplayName(), lumifyVisibility.getVisibility())
        .setConceptGraphVertexId(concept.getTitle(), lumifyVisibility.getVisibility())
        .setVertexId(vertex.getId().toString(), lumifyVisibility.getVisibility())
        .setEdgeId(edge.getId().toString(), lumifyVisibility.getVisibility());
    termMentionRepository.save(termMention);

    vertexMutation.addPropertyValue(
        graph.getIdGenerator().nextId().toString(),
        LumifyProperties.ROW_KEY.getPropertyName(),
        termMentionRowKey.toString(),
        metadata,
        lumifyVisibility.getVisibility());
    vertexMutation.save(authorizations);

    this.graph.flush();
    workQueueRepository.pushTextUpdated(artifactId);

    workQueueRepository.pushElement(edge);

    JSONObject result = new JSONObject();
    result.put("success", true);
    respondWithJson(response, result);
  }
示例#9
0
 static String getWikipediaPageToPageEdgeId(Vertex pageVertex, Vertex linkedPageVertex) {
   return WIKIPEDIA_LINK_ID_PREFIX
       + getWikipediaPageTitleFromId(pageVertex.getId())
       + "_"
       + getWikipediaPageTitleFromId(linkedPageVertex.getId());
 }
  @Test
  public void testEntities() {
    int startingVertexCount = graph.getAllVertices().size();
    int startingEdgeCount = graph.getAllEdges().size();

    String workspaceId = "testWorkspaceId";
    idGenerator.push(workspaceId);
    idGenerator.push(workspaceId + "_to_" + user1.getUserId());

    Workspace workspace = workspaceRepository.add("workspace1", user1);
    assertEquals(
        startingVertexCount + 1, graph.getAllVertices().size()); // +1 = the workspace vertex
    assertEquals(
        startingEdgeCount + 1,
        graph.getAllEdges().size()); // +1 = the edges between workspaces and users

    try {
      workspaceRepository.updateEntityOnWorkspace(
          workspace, entity1Vertex.getId(), true, 100, 100, user2);
      fail("user2 should not have write access to workspace");
    } catch (LumifyAccessDeniedException ex) {
      assertEquals(user2, ex.getUser());
      assertEquals(workspace.getId(), ex.getResourceId());
    }

    idGenerator.push(workspaceId + "_to_" + entity1Vertex.getId());
    workspaceRepository.updateEntityOnWorkspace(
        workspace, entity1Vertex.getId(), true, 100, 200, user1);
    assertEquals(
        startingVertexCount + 1, graph.getAllVertices().size()); // +1 = the workspace vertex
    assertEquals(
        startingEdgeCount + 2,
        graph.getAllEdges().size()); // +2 = the edges between workspaces, users, and entities

    workspaceRepository.updateEntityOnWorkspace(
        workspace, entity1Vertex.getId(), true, 200, 300, user1);
    assertEquals(
        startingVertexCount + 1, graph.getAllVertices().size()); // +1 = the workspace vertex
    assertEquals(
        startingEdgeCount + 2,
        graph.getAllEdges().size()); // +2 = the edges between workspaces, users, and entities

    List<WorkspaceEntity> entities = workspaceRepository.findEntities(workspace, user1);
    assertEquals(1, entities.size());
    assertEquals(entity1Vertex.getId(), entities.get(0).getEntityVertexId());
    assertEquals(200, entities.get(0).getGraphPositionX().intValue());
    assertEquals(300, entities.get(0).getGraphPositionY().intValue());

    try {
      workspaceRepository.findEntities(workspace, user2);
      fail("user2 should not have read access to workspace");
    } catch (LumifyAccessDeniedException ex) {
      assertEquals(user2, ex.getUser());
      assertEquals(workspace.getId(), ex.getResourceId());
    }

    try {
      workspaceRepository.softDeleteEntityFromWorkspace(workspace, entity1Vertex.getId(), user2);
      fail("user2 should not have write access to workspace");
    } catch (LumifyAccessDeniedException ex) {
      assertEquals(user2, ex.getUser());
      assertEquals(workspace.getId(), ex.getResourceId());
    }

    workspaceRepository.softDeleteEntityFromWorkspace(workspace, entity1Vertex.getId(), user1);
    assertEquals(
        startingVertexCount + 1, graph.getAllVertices().size()); // +1 = the workspace vertex
    Map<String, InMemoryEdge> edgesAfterDelete = graph.getAllEdges();
    assertEquals(
        startingEdgeCount + 2, edgesAfterDelete.size()); // +1 = the edges between workspaces, users
    boolean foundRemovedEdge = false;
    for (InMemoryEdge edge : edgesAfterDelete.values()) {
      if (edge.getLabel().equals(workspaceToEntityRelationship.getIRI())) {
        assertEquals(
            false, WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_VISIBLE.getPropertyValue(edge));
        foundRemovedEdge = true;
      }
    }
    assertTrue(foundRemovedEdge);
  }
示例#11
0
  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain)
      throws Exception {
    long totalStartTime = System.nanoTime();
    final String query;
    final String filter = getRequiredParameter(request, "filter");
    final int offset = (int) getOptionalParameterLong(request, "offset", 0);
    final int size = (int) getOptionalParameterLong(request, "size", DEFAULT_RESULT_COUNT);
    final String conceptType = getOptionalParameter(request, "conceptType");
    final String getLeafNodes = getOptionalParameter(request, "leafNodes");
    final String relatedToVertexId = getOptionalParameter(request, "relatedToVertexId");
    if (relatedToVertexId == null) {
      query = getRequiredParameter(request, "q");
    } else {
      query = getOptionalParameter(request, "q");
    }

    long startTime = System.nanoTime();

    User user = getUser(request);
    Authorizations authorizations = getAuthorizations(request, user);
    String workspaceId = getActiveWorkspaceId(request);
    ModelUserContext modelUserContext =
        userRepository.getModelUserContext(authorizations, workspaceId);

    JSONArray filterJson = new JSONArray(filter);

    ontologyRepository.resolvePropertyIds(filterJson);

    graph.flush();

    LOGGER.debug("search %s\n%s", query, filterJson.toString(2));

    Query graphQuery;
    if (relatedToVertexId == null) {
      graphQuery = graph.query(query, authorizations);
    } else if (query == null || StringUtils.isBlank(query)) {
      graphQuery = graph.getVertex(relatedToVertexId, authorizations).query(authorizations);
    } else {
      graphQuery = graph.getVertex(relatedToVertexId, authorizations).query(query, authorizations);
    }

    for (int i = 0; i < filterJson.length(); i++) {
      JSONObject obj = filterJson.getJSONObject(i);
      if (obj.length() > 0) {
        updateQueryWithFilter(graphQuery, obj);
      }
    }

    if (conceptType != null) {
      Concept concept = ontologyRepository.getConceptByIRI(conceptType);
      if (getLeafNodes == null || !getLeafNodes.equals("false")) {
        List<Concept> leafNodeList = ontologyRepository.getAllLeafNodesByConcept(concept);
        if (leafNodeList.size() > 0) {
          String[] conceptIds = new String[leafNodeList.size()];
          int count = 0;
          for (Concept c : leafNodeList) {
            conceptIds[count] = c.getTitle();
            count++;
          }
          graphQuery.has(CONCEPT_TYPE.getPropertyName(), Compare.IN, conceptIds);
        }
      } else {
        graphQuery.has(CONCEPT_TYPE.getPropertyName(), conceptType);
      }
    }

    graphQuery.limit(size);
    graphQuery.skip(offset);
    Iterable<Vertex> searchResults;
    try {
      searchResults = graphQuery.vertices();
    } catch (SearchPhaseExecutionException ex) {
      respondWithBadRequest(response, "q", "Invalid Query");
      return;
    }

    Map<Object, Double> scores = null;
    if (searchResults instanceof IterableWithScores) {
      scores = ((IterableWithScores) searchResults).getScores();
    }

    long retrievalStartTime = System.nanoTime();
    List<JSONObject> verticesJsonList = new ArrayList<JSONObject>();
    for (Vertex vertex : searchResults) {
      JSONObject vertexJson = JsonSerializer.toJson(vertex, workspaceId);
      if (scores != null) {
        vertexJson.put("score", scores.get(vertex.getId()));
      }
      vertexJson.put(
          "detectedObjects",
          detectedObjectRepository.toJSON(vertex, modelUserContext, authorizations, workspaceId));
      verticesJsonList.add(vertexJson);
    }
    long retrievalEndTime = System.nanoTime();

    Collections.sort(
        verticesJsonList,
        new Comparator<JSONObject>() {
          @Override
          public int compare(JSONObject o1, JSONObject o2) {
            double score1 = o1.optDouble("score", 0.0);
            double score2 = o2.optDouble("score", 0.0);
            return -Double.compare(score1, score2);
          }
        });

    JSONArray verticesJson = new JSONArray();
    for (JSONObject vertexJson : verticesJsonList) {
      verticesJson.put(vertexJson);
    }

    long totalEndTime = System.nanoTime();

    JSONObject results = new JSONObject();
    results.put("vertices", verticesJson);
    results.put("nextOffset", offset + size);
    results.put("retrievalTime", retrievalEndTime - retrievalStartTime);
    results.put("totalTime", totalEndTime - totalStartTime);

    if (searchResults instanceof IterableWithTotalHits) {
      results.put("totalHits", ((IterableWithTotalHits) searchResults).getTotalHits());
    }
    if (searchResults instanceof IterableWithSearchTime) {
      results.put(
          "searchTime", ((IterableWithSearchTime) searchResults).getSearchTimeNanoSeconds());
    }

    long endTime = System.nanoTime();
    LOGGER.info(
        "Search for \"%s\" found %d vertices in %dms",
        query, verticesJsonList.size(), (endTime - startTime) / 1000 / 1000);

    respondWithJson(response, results);
  }
示例#12
0
  private TermMentionWithGraphVertex saveTermMention(
      Vertex artifactGraphVertex,
      TermMention termMention,
      String workspaceId,
      String visibilitySource) {
    LOGGER.debug(
        "Saving term mention '%s':%s:%s (%d:%d)",
        termMention.getSign(),
        termMention.getOntologyClassUri(),
        termMention.getPropertyKey(),
        termMention.getStart(),
        termMention.getEnd());
    Vertex vertex = null;
    if (visibilitySource == null) {
      visibilitySource = termMention.getVisibility().getVisibilityString();
    }

    JSONObject visibilityJson = new JSONObject();
    visibilityJson.put(VisibilityTranslator.JSON_SOURCE, visibilitySource);
    Visibility visibility = visibilityTranslator.toVisibility(visibilityJson).getVisibility();

    Visibility visibilityWithWorkspaceId;
    JSONObject visibilityJsonWithWorkspaceId;
    if (!workspaceId.equals("")) {
      visibilityJsonWithWorkspaceId =
          GraphUtil.updateVisibilitySourceAndAddWorkspaceId(null, visibilitySource, workspaceId);
      visibilityWithWorkspaceId =
          visibilityTranslator.toVisibility(visibilityJsonWithWorkspaceId).getVisibility();
    } else {
      visibilityWithWorkspaceId = visibility;
      visibilityJsonWithWorkspaceId = visibilityJson;
    }

    TermMentionRowKey termMentionRowKey =
        new TermMentionRowKey(
            artifactGraphVertex.getId().toString(),
            termMention.getPropertyKey(),
            termMention.getStart(),
            termMention.getEnd());
    TermMentionModel termMentionModel = new TermMentionModel(termMentionRowKey);
    termMentionModel.getMetadata().setSign(termMention.getSign(), visibility);
    termMentionModel
        .getMetadata()
        .setOntologyClassUri(termMention.getOntologyClassUri(), visibility);
    if (termMention.getProcess() != null && !termMention.getProcess().equals("")) {
      termMentionModel.getMetadata().setAnalyticProcess(termMention.getProcess(), visibility);
    }

    Concept concept = ontologyRepository.getConceptByIRI(termMention.getOntologyClassUri());
    if (concept == null) {
      LOGGER.error("Could not find ontology graph vertex '%s'", termMention.getOntologyClassUri());
      return null;
    }
    termMentionModel.getMetadata().setConceptGraphVertexId(concept.getTitle(), visibility);

    if (termMention.isResolved()) {
      String title = termMention.getSign();
      ElementMutation<Vertex> vertexElementMutation;
      if (termMention.getUseExisting()) {
        graph.flush(); // make sure the previous term mentions have made it into the graph
        if (termMention.getId() != null) {
          vertex = graph.getVertex(termMention.getId(), getAuthorizations());
        } else {
          vertex =
              singleOrDefault(
                  graph
                      .query(getAuthorizations())
                      .has(LumifyProperties.TITLE.getPropertyName(), title)
                      .has(LumifyProperties.CONCEPT_TYPE.getPropertyName(), concept.getTitle())
                      .vertices(),
                  null);
        }
      }

      Map<String, Object> metadata = new HashMap<String, Object>();
      LumifyVisibilityProperties.VISIBILITY_JSON_PROPERTY.setMetadata(
          metadata, visibilityJsonWithWorkspaceId);

      if (vertex == null) {
        if (termMention.getId() != null) {
          vertexElementMutation =
              graph.prepareVertex(termMention.getId(), visibilityWithWorkspaceId);
        } else {
          vertexElementMutation = graph.prepareVertex(visibilityWithWorkspaceId);
        }
        LumifyProperties.TITLE.setProperty(
            vertexElementMutation, title, metadata, visibilityWithWorkspaceId);
        LumifyProperties.CONCEPT_TYPE.setProperty(
            vertexElementMutation, concept.getTitle(), metadata, visibilityWithWorkspaceId);
      } else {
        vertexElementMutation = vertex.prepareMutation();
      }

      for (TermMention.TermMentionProperty termMentionProperty : termMention.getNewProperties()) {
        vertexElementMutation.addPropertyValue(
            termMentionProperty.getKey(),
            termMentionProperty.getName(),
            termMentionProperty.getValue(),
            metadata,
            visibilityWithWorkspaceId);
      }

      LumifyVisibilityProperties.VISIBILITY_JSON_PROPERTY.setProperty(
          vertexElementMutation,
          visibilityJsonWithWorkspaceId,
          metadata,
          visibilityWithWorkspaceId);
      vertexElementMutation.addPropertyValue(
          graph.getIdGenerator().nextId(),
          LumifyProperties.ROW_KEY.getPropertyName(),
          termMentionRowKey.toString(),
          metadata,
          visibilityWithWorkspaceId);

      if (!(vertexElementMutation instanceof ExistingElementMutation)) {
        vertex = vertexElementMutation.save(getAuthorizations());
        auditRepository.auditVertexElementMutation(
            AuditAction.UPDATE,
            vertexElementMutation,
            vertex,
            termMention.getProcess(),
            getUser(),
            visibilityWithWorkspaceId);
      } else {
        auditRepository.auditVertexElementMutation(
            AuditAction.UPDATE,
            vertexElementMutation,
            vertex,
            termMention.getProcess(),
            getUser(),
            visibilityWithWorkspaceId);
        vertex = vertexElementMutation.save(getAuthorizations());
      }

      // TODO: a better way to check if the same edge exists instead of looking it up every time?
      Edge edge =
          singleOrDefault(
              artifactGraphVertex.getEdges(
                  vertex, Direction.OUT, artifactHasEntityIri, getAuthorizations()),
              null);
      if (edge == null) {
        edge =
            graph.addEdge(
                artifactGraphVertex, vertex, artifactHasEntityIri, visibility, getAuthorizations());
        LumifyVisibilityProperties.VISIBILITY_JSON_PROPERTY.setProperty(
            edge,
            visibilityJsonWithWorkspaceId,
            metadata,
            visibilityWithWorkspaceId,
            getAuthorizations());
        auditRepository.auditRelationship(
            AuditAction.CREATE,
            artifactGraphVertex,
            vertex,
            edge,
            termMention.getProcess(),
            "",
            getUser(),
            visibilityWithWorkspaceId);
      }

      graph.flush();
      if (workspaceId != null && !workspaceId.equals("")) {
        Workspace workspace = workspaceRepository.findById(workspaceId, getUser());
        workspaceRepository.updateEntityOnWorkspace(
            workspace, vertex.getId(), null, null, null, getUser());
      }

      termMentionModel
          .getMetadata()
          .setVertexId(vertex.getId().toString(), visibility)
          .setEdgeId(edge.getId().toString(), visibility);
    }

    getTermMentionRepository().save(termMentionModel, FlushFlag.NO_FLUSH);
    return new TermMentionWithGraphVertex(termMentionModel, vertex);
  }
示例#13
0
 public SecureGraphWorkspace(Vertex workspaceVertex) {
   this.displayTitle = WorkspaceLumifyProperties.TITLE.getPropertyValue(workspaceVertex);
   this.workspaceId = workspaceVertex.getId().toString();
   this.workspaceVertex = workspaceVertex;
 }