@Test
 public void testConvertMapToMapWithSameType() {
   Object result =
       converter.convertToResultType(
           MapUtil.map("test", 1, "test2", 2), new TypeInformation(MapUtil.map("test", 0)));
   assertEquals(MapUtil.map("test", 1, "test2", 2), result);
 }
  public void importa(BatchInserter inserter, LuceneBatchInserterIndexProvider indexProvider) {

    BatchInserterIndex pessoas =
        indexProvider.nodeIndex("pessoas", MapUtil.stringMap("type", "fulltext"));

    Scanner sc = new Scanner(ImportadorPessoas.class.getResourceAsStream("/import/pessoas"));

    System.out.println("Início da importação das pessoas");
    while (sc.hasNextLine()) {
      String linha = sc.nextLine();
      String[] informacoesDePessoa = linha.split(";");
      long id = Long.parseLong(informacoesDePessoa[0]);
      String nome = informacoesDePessoa[1];
      Integer idade = Integer.parseInt(informacoesDePessoa[2]);

      Map<String, Object> propriedades = MapUtil.map("nome", nome, "idade", idade);

      inserter.createNode(id, propriedades);
      pessoas.add(id, MapUtil.map("nome", nome));
      inserter.createRelationship(0, id, Relacionamentos.PESSOA, null);
    }

    pessoas.flush();

    System.out.println("Fim da importação das pessoas");
  }
 @Test
 public void shouldBeAbleToTraverseEverything() {
   long startNode = createBasicTraversableGraph();
   List<Object> hits =
       serialize(
           actions.traverse(
               startNode,
               MapUtil.map(
                   "return_filter",
                   MapUtil.map("language", "javascript", "body", "true;"),
                   "max_depth",
                   10),
               TraverserReturnType.node));
   assertEquals(6, hits.size());
   hits =
       serialize(
           actions.traverse(
               startNode,
               MapUtil.map(
                   "return_filter",
                   MapUtil.map("language", "builtin", "name", "all"),
                   "max_depth",
                   10),
               TraverserReturnType.node));
   assertEquals(6, hits.size());
 }
 @Test
 public void shouldBeAbleToTraverseWithMaxDepthAndPruneEvaluatorCombined() {
   long startNode = createBasicTraversableGraph();
   List<Object> hits =
       serialize(
           actions.traverse(
               startNode,
               MapUtil.map(
                   "max_depth",
                   2,
                   "prune_evaluator",
                   MapUtil.map(
                       "language",
                       "javascript",
                       "body",
                       "position.endNode().getProperty('name').equals('Emil')")),
               TraverserReturnType.node));
   assertEquals(3, hits.size());
   hits =
       serialize(
           actions.traverse(
               startNode,
               MapUtil.map(
                   "max_depth",
                   1,
                   "prune_evaluator",
                   MapUtil.map(
                       "language",
                       "javascript",
                       "body",
                       "position.endNode().getProperty('name').equals('Emil')")),
               TraverserReturnType.node));
   assertEquals(2, hits.size());
 }
 @Test
 public void testConvertDifferentMapsWithSameType() {
   Hashtable<String, String> table = new Hashtable<String, String>();
   table.put("testkey", "testvalue");
   Object result =
       converter.convertToResultType(table, new TypeInformation(MapUtil.map("test", "test")));
   assertEquals(MapUtil.map("testkey", "testvalue"), result);
 }
 @Test
 public void testConvertJSONDataToRelationship() {
   Object result =
       converter.convertToResultType(
           MapUtil.map(
               "self",
               "http://localhost:7474/db/data/relationship/2",
               "data",
               MapUtil.map("propname", "testprop")),
           new TypeInformation(RestRelationship.class));
   assertEquals(RestRelationship.class, result.getClass());
   assertEquals("testprop", ((Relationship) result).getProperty("propname"));
 }
示例#7
0
  /** Remove all entries with a given node, key and value from an index. */
  @Documented
  @Test
  public void shouldBeAbleToRemoveIndexingByIdAndKeyAndValue() {
    String key1 = "kvkey1";
    String key2 = "kvkey2";
    String value1 = "value1";
    String value2 = "value2";
    String indexName = "kvnode";
    long node =
        helper.createNode(MapUtil.map(key1, value1, key1, value2, key2, value1, key2, value2));
    helper.addNodeToIndex(indexName, key1, value1, node);
    helper.addNodeToIndex(indexName, key1, value2, node);
    helper.addNodeToIndex(indexName, key2, value1, node);
    helper.addNodeToIndex(indexName, key2, value2, node);

    gen()
        .noGraph()
        .expectedStatus(204)
        .delete(
            functionalTestHelper.nodeIndexUri()
                + indexName
                + "/"
                + key1
                + "/"
                + value1
                + "/"
                + node);

    assertEquals(0, helper.getIndexedNodes(indexName, key1, value1).size());
    assertEquals(1, helper.getIndexedNodes(indexName, key1, value2).size());
    assertEquals(1, helper.getIndexedNodes(indexName, key2, value1).size());
    assertEquals(1, helper.getIndexedNodes(indexName, key2, value2).size());
  }
示例#8
0
  public void importFromFile(String filePath) throws IOException {
    Map<String, Long> cache = new HashMap<String, Long>(COUNT);
    final File storeDir = new File(this.path);
    org.apache.commons.io.FileUtils.deleteDirectory(storeDir);
    BatchInserter batchInserter = new BatchInserterImpl(storeDir.getAbsolutePath());
    final BatchInserterIndexProvider indexProvider =
        new LuceneBatchInserterIndexProvider(batchInserter);
    final BatchInserterIndex index =
        indexProvider.nodeIndex("nodes", MapUtil.stringMap("type", "exact"));
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    String line = null;
    int nodes = 0;
    long time = System.currentTimeMillis();
    long batchTime = time;
    while ((line = reader.readLine()) != null) {
      final String[] nodeNames = line.split("\\|");
      final String name = nodeNames[0];
      final Map<String, Object> props = MapUtil.map("name", name);
      final long node = batchInserter.createNode(props);
      index.add(node, props);
      cache.put(name, node);
      nodes++;
      if ((nodes % REPORT_COUNT) == 0) {
        System.out.printf(
            "%d nodes created. Took %d %n", nodes, (System.currentTimeMillis() - batchTime));
        batchTime = System.currentTimeMillis();
      }
    }

    System.out.println("Creating nodes took " + (System.currentTimeMillis() - time) / 1000);
    index.flush();
    reader.close();
    reader = new BufferedReader(new FileReader(filePath));
    int rels = 0;
    time = System.currentTimeMillis();
    batchTime = time;
    String relationshipType = "KNOWS";
    while ((line = reader.readLine()) != null) {
      final String[] nodeNames = line.split("\\|");
      final String name = nodeNames[0];
      // final Long from = index.get("name", name).getSingle();
      Long from = cache.get(name);
      for (int j = 1; j < nodeNames.length; j++) {
        // final Long to = index.get("name", nodeNames[j]).getSingle();
        final Long to = cache.get(name);
        batchInserter.createRelationship(
            from, to, DynamicRelationshipType.withName(relationshipType), null);
      }
      rels++;
      if ((rels % REPORT_COUNT) == 0) {
        System.out.printf(
            "%d relationships created. Took %d %n", rels, (System.currentTimeMillis() - batchTime));
        batchTime = System.currentTimeMillis();
      }
    }
    System.out.println("Creating relationships took " + (System.currentTimeMillis() - time) / 1000);
    indexProvider.shutdown();
    batchInserter.shutdown();
  }
 @Test
 public void shouldBeAbleToTraverseDepthTwo() {
   long startNode = createBasicTraversableGraph();
   List<Object> hits =
       serialize(
           actions.traverse(startNode, MapUtil.map("max_depth", 2), TraverserReturnType.node));
   assertEquals(3, hits.size());
 }
示例#10
0
 @Test
 public void shouldBeAbleToUseCustomReturnFilter() {
   long startNode = createBasicTraversableGraph();
   List<Object> hits =
       serialize(
           actions.traverse(
               startNode,
               MapUtil.map(
                   "prune_evaluator",
                   MapUtil.map("language", "builtin", "name", "none"),
                   "return_filter",
                   MapUtil.map(
                       "language",
                       "javascript",
                       "body",
                       "position.endNode().getProperty( 'name' ).contains( 'o' )")),
               TraverserReturnType.node));
   assertEquals(3, hits.size());
 }
 @Override
 public <T> void addToIndex(T entity, RestIndex index, String key, Object value) {
   final RestEntity restEntity = (RestEntity) entity;
   String uri = restEntity.getUri();
   if (value instanceof ValueContext) {
     value = ((ValueContext) value).getCorrectValue();
   }
   final Map<String, Object> data = MapUtil.map("key", key, "value", value, "uri", uri);
   final RequestResult result = restRequest.post(index.indexPath(), data);
 }
示例#12
0
  private static long createGenomeElementNode(
      String version,
      String comment,
      String definition,
      BatchInserter inserter,
      BatchInserterIndex genomeElementVersionIndex,
      BatchInserterIndex nodeTypeIndex) {

    genomeElementProperties.put(GenomeElementNode.VERSION_PROPERTY, version);
    genomeElementProperties.put(GenomeElementNode.COMMENT_PROPERTY, comment);
    genomeElementProperties.put(GenomeElementNode.DEFINITION_PROPERTY, definition);

    long genomeElementId = inserter.createNode(genomeElementProperties);
    genomeElementVersionIndex.add(
        genomeElementId, MapUtil.map(GenomeElementNode.GENOME_ELEMENT_VERSION_INDEX, version));
    nodeTypeIndex.add(
        genomeElementId,
        MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, GenomeElementNode.NODE_TYPE));

    return genomeElementId;
  }
 @Test
 public void testConvertJSONDataToFullPath() {
   Map<String, Object> node1 =
       MapUtil.map(
           "self",
           "http://localhost:7474/db/data/node/1",
           "data",
           MapUtil.map("propname", "testprop1"));
   Map<String, Object> node2 =
       MapUtil.map(
           "self",
           "http://localhost:7474/db/data/node/2",
           "data",
           MapUtil.map("propname", "testprop2"));
   Map<String, Object> relationship1 =
       MapUtil.map(
           "self",
           "http://localhost:7474/db/data/relationship/1",
           "data",
           MapUtil.map("propname", "testproprel1"));
   Map<String, Object> path = new HashMap<String, Object>();
   path.put("start", node1);
   path.put("nodes", asList(node1, node2));
   path.put("length", 1);
   path.put("relationships", asList(relationship1));
   path.put("end", node2);
   Object result = converter.convertToResultType(path, new TypeInformation(Path.class));
   assertEquals(SimplePath.class, result.getClass());
   assertEquals("testprop1", ((SimplePath) result).startNode().getProperty("propname"));
   assertEquals("testprop2", ((SimplePath) result).endNode().getProperty("propname"));
   assertEquals("testproprel1", ((SimplePath) result).lastRelationship().getProperty("propname"));
 }
示例#14
0
  @Test
  public void shouldBeAbleToIndexNode() {
    String key = "mykey";
    String value = "myvalue";
    long nodeId = graphdbHelper.createNode();
    String indexName = "node";

    actions.createNodeIndex(MapUtil.map("name", indexName));

    assertFalse(serialize(actions.getIndexedNodes(indexName, key, value)).iterator().hasNext());
    actions.addToNodeIndex(indexName, key, value, nodeId);
    assertEquals(Arrays.asList(nodeId), graphdbHelper.getIndexedNodes(indexName, key, value));
  }
  private long createListOfNodes(int numberOfNodes) {
    Transaction tx = database.getGraph().beginTx();
    try {
      long zerothNode = helper.createNode(MapUtil.map("name", String.valueOf(0)));
      long previousNodeId = zerothNode;
      for (int i = 1; i < numberOfNodes; i++) {
        long currentNodeId = helper.createNode(MapUtil.map("name", String.valueOf(i)));
        database
            .getGraph()
            .getNodeById(previousNodeId)
            .createRelationshipTo(
                database.getGraph().getNodeById(currentNodeId),
                DynamicRelationshipType.withName("PRECEDES"));
        previousNodeId = currentNodeId;
      }

      tx.success();
      return zerothNode;
    } finally {
      tx.finish();
    }
  }
示例#16
0
 public Map getQueryStatistics() {
   final Map<String, Object> stats =
       MapUtil.map(
           "rows", getRowCount(),
           "time", getTime());
   if (queryStatistics != null && queryStatistics.containsUpdates()) {
     stats.put("containsUpdates", queryStatistics.containsUpdates());
     stats.put("nodesDeleted", queryStatistics.getDeletedNodes());
     stats.put("relationshipsDeleted", queryStatistics.getDeletedRelationships());
     stats.put("nodesCreated", queryStatistics.getNodesCreated());
     stats.put("relationshipsCreated", queryStatistics.getRelationshipsCreated());
     stats.put("propertiesSet", queryStatistics.getPropertiesSet());
     stats.put("text", queryStatistics.toString());
   }
   return stats;
 }
示例#17
0
  private static long createGenomeElementNode(
      String version,
      String comment,
      String definition,
      BatchInserter inserter,
      BatchInserterIndex index) {

    genomeElementProperties.put(GenomeElementNode.VERSION_PROPERTY, version);
    genomeElementProperties.put(GenomeElementNode.COMMENT_PROPERTY, comment);
    genomeElementProperties.put(GenomeElementNode.DEFINITION_PROPERTY, definition);

    long genomeElementId = inserter.createNode(genomeElementProperties);
    index.add(
        genomeElementId, MapUtil.map(GenomeElementNode.GENOME_ELEMENT_VERSION_INDEX, version));
    return genomeElementId;
  }
示例#18
0
  @Test
  public void orderedResultsAreSupersetOfUnordered() throws Exception {
    // Given
    String indexName = "bobTheIndex";
    String key = "Name";
    String value = "Builder";
    long node = helper.createNode(MapUtil.map(key, value));
    helper.addNodeToIndex(indexName, key, value, node);
    helper.addNodeToIndex(indexName, "Gender", "Male", node);

    String entity =
        gen()
            .expectedStatus(200)
            .get(
                functionalTestHelper.indexNodeUri(indexName)
                    + "?query=Name:Build~0.1%20AND%20Gender:Male")
            .entity();

    Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue(entity);
    LinkedHashMap<String, String> nodeMapUnordered = (LinkedHashMap) hits.iterator().next();

    // When
    entity =
        gen()
            .expectedStatus(200)
            .get(
                functionalTestHelper.indexNodeUri(indexName)
                    + "?query=Name:Build~0.1%20AND%20Gender:Male&order=score")
            .entity();

    hits = (Collection<?>) JsonHelper.jsonToSingleValue(entity);
    LinkedHashMap<String, String> nodeMapOrdered = (LinkedHashMap) hits.iterator().next();

    // Then
    for (Map.Entry<String, String> unorderedEntry : nodeMapUnordered.entrySet()) {
      assertEquals(
          "wrong entry for key: " + unorderedEntry.getKey(),
          unorderedEntry.getValue(),
          nodeMapOrdered.get(unorderedEntry.getKey()));
    }
    assertTrue(
        "There should be only one extra value for the ordered map",
        nodeMapOrdered.size() == nodeMapUnordered.size() + 1);
  }
示例#19
0
  @Test
  public void shouldBeAbleToGetShortestPaths() throws Exception {
    long[] nodes = createMoreComplexGraph();

    // /paths
    List<Object> result =
        serialize(
            actions.findPaths(
                nodes[0],
                nodes[1],
                MapUtil.map(
                    "max_depth",
                    2,
                    "algorithm",
                    "shortestPath",
                    "relationships",
                    MapUtil.map("type", "to", "direction", "out"))));
    assertPaths(2, nodes, 2, result);

    // /path
    Map<String, Object> path =
        serialize(
            actions.findSinglePath(
                nodes[0],
                nodes[1],
                MapUtil.map(
                    "max_depth",
                    2,
                    "algorithm",
                    "shortestPath",
                    "relationships",
                    MapUtil.map("type", "to", "direction", "out"))));
    assertPaths(1, nodes, 2, Arrays.<Object>asList(path));

    // /path {single: false} (has no effect)
    path =
        serialize(
            actions.findSinglePath(
                nodes[0],
                nodes[1],
                MapUtil.map(
                    "max_depth",
                    2,
                    "algorithm",
                    "shortestPath",
                    "relationships",
                    MapUtil.map("type", "to", "direction", "out"),
                    "single",
                    false)));
    assertPaths(1, nodes, 2, Arrays.<Object>asList(path));
  }
示例#20
0
  /**
   * Find node by query.
   *
   * <p>The query language used here depends on what type of index you are querying. The default
   * index type is Lucene, in which case you should use the Lucene query language here. Below an
   * example of a fuzzy search over multiple keys.
   *
   * <p>See: {lucene-base-uri}/queryparsersyntax.html
   *
   * <p>Getting the results with a predefined ordering requires adding the parameter
   *
   * <p>`order=ordering`
   *
   * <p>where ordering is one of index, relevance or score. In this case an additional field will be
   * added to each result, named score, that holds the float value that is the score reported by the
   * query result.
   */
  @Documented
  @Test
  public void shouldAddToIndexAndRetrieveItByQuery() throws PropertyValueException {
    String indexName = "bobTheIndex";
    String key = "Name";
    String value = "Builder";
    long node = helper.createNode(MapUtil.map(key, value));
    helper.addNodeToIndex(indexName, key, value, node);
    helper.addNodeToIndex(indexName, "Gender", "Male", node);

    String entity =
        gen()
            .noGraph()
            .expectedStatus(200)
            .get(
                functionalTestHelper.indexNodeUri(indexName)
                    + "?query=Name:Build~0.1%20AND%20Gender:Male")
            .entity();

    Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue(entity);
    assertEquals(1, hits.size());
    LinkedHashMap<String, String> nodeMap = (LinkedHashMap) hits.iterator().next();
    assertNull("score should not be present when not explicitly ordering", nodeMap.get("score"));
  }
示例#21
0
  private long createBasicTraversableGraph() {
    // (Root)
    // / \
    // (Mattias) (Johan)
    // / / \
    // (Emil) (Peter) (Tobias)

    long startNode = graphdbHelper.createNode(MapUtil.map("name", "Root"));
    long child1_l1 = graphdbHelper.createNode(MapUtil.map("name", "Mattias"));
    graphdbHelper.createRelationship("knows", startNode, child1_l1);
    long child2_l1 = graphdbHelper.createNode(MapUtil.map("name", "Johan"));
    graphdbHelper.createRelationship("knows", startNode, child2_l1);
    long child1_l2 = graphdbHelper.createNode(MapUtil.map("name", "Emil"));
    graphdbHelper.createRelationship("knows", child2_l1, child1_l2);
    long child1_l3 = graphdbHelper.createNode(MapUtil.map("name", "Peter"));
    graphdbHelper.createRelationship("knows", child1_l2, child1_l3);
    long child2_l3 = graphdbHelper.createNode(MapUtil.map("name", "Tobias"));
    graphdbHelper.createRelationship("loves", child1_l2, child2_l3);
    return startNode;
  }
示例#22
0
  public static void main(String[] args) {

    if (args.length != 3) {
      System.out.println(
          "This program expects the following parameters: \n"
              + "1. Folder name with all the .gbk files \n"
              + "2. Bio4j DB folder \n"
              + "3. batch inserter .properties file");
    } else {

      File currentFolder = new File(args[0]);

      File[] files = currentFolder.listFiles();

      BatchInserter inserter = null;
      BatchInserterIndexProvider indexProvider = null;

      // ----------------------------------------------------------------------------------
      // ---------------------initializing node type properties----------------------------
      genomeElementProperties.put(
          GenomeElementNode.NODE_TYPE_PROPERTY, GenomeElementNode.NODE_TYPE);
      geneProperties.put(GeneNode.NODE_TYPE_PROPERTY, GeneNode.NODE_TYPE);
      cdsProperties.put(CDSNode.NODE_TYPE_PROPERTY, CDSNode.NODE_TYPE);
      miscRnaProperties.put(MiscRNANode.NODE_TYPE_PROPERTY, MiscRNANode.NODE_TYPE);
      mRnaProperties.put(MRNANode.NODE_TYPE_PROPERTY, MRNANode.NODE_TYPE);
      ncRnaProperties.put(NcRNANode.NODE_TYPE_PROPERTY, NcRNANode.NODE_TYPE);
      rRnaProperties.put(RRNANode.NODE_TYPE_PROPERTY, RRNANode.NODE_TYPE);
      tmRnaProperties.put(TmRNANode.NODE_TYPE_PROPERTY, TmRNANode.NODE_TYPE);
      tRnaProperties.put(TRNANode.NODE_TYPE_PROPERTY, TRNANode.NODE_TYPE);
      // ----------------------------------------------------------------------------------
      // ----------------------------------------------------------------------------------

      try {
        // This block configures the logger with handler and formatter
        fh = new FileHandler("ImportRefSeq.log", false);

        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.addHandler(fh);
        logger.setLevel(Level.ALL);

        // create the batch inserter
        inserter = BatchInserters.inserter(args[1], MapUtil.load(new File(args[2])));

        // create the batch index service
        indexProvider = new LuceneBatchInserterIndexProvider(inserter);

        // -----------------create batch indexes----------------------------------
        // ----------------------------------------------------------------------
        BatchInserterIndex genomeElementVersionIndex =
            indexProvider.nodeIndex(
                GenomeElementNode.GENOME_ELEMENT_VERSION_INDEX,
                MapUtil.stringMap(PROVIDER_ST, LUCENE_ST, TYPE_ST, EXACT_ST));
        BatchInserterIndex nodeTypeIndex =
            indexProvider.nodeIndex(
                Bio4jManager.NODE_TYPE_INDEX_NAME,
                MapUtil.stringMap(PROVIDER_ST, LUCENE_ST, TYPE_ST, EXACT_ST));

        for (File file : files) {
          if (file.getName().endsWith(".gbff")) {

            logger.log(Level.INFO, ("file: " + file.getName()));

            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = null;

            while ((line = reader.readLine()) != null) {

              // this is the first line where the locus is
              String accessionSt = "";
              String definitionSt = "";
              String versionSt = "";
              String commentSt = "";
              StringBuilder seqStBuilder = new StringBuilder();

              ArrayList<String> cdsList = new ArrayList<String>();
              ArrayList<String> geneList = new ArrayList<String>();
              ArrayList<String> miscRnaList = new ArrayList<String>();
              ArrayList<String> mRnaList = new ArrayList<String>();
              ArrayList<String> ncRnaList = new ArrayList<String>();
              ArrayList<String> rRnaList = new ArrayList<String>();
              ArrayList<String> tmRnaList = new ArrayList<String>();
              ArrayList<String> tRnaList = new ArrayList<String>();

              boolean originFound = false;

              // Now I get all the lines till I reach the string '//'
              do {
                boolean readLineFlag = true;

                if (line.startsWith(GBCommon.LOCUS_STR)) {
                  // do nothing right now
                } else if (line.startsWith(GBCommon.ACCESSION_STR)) {

                  accessionSt = line.split(GBCommon.ACCESSION_STR)[1].trim();

                } else if (line.startsWith(GBCommon.VERSION_STR)) {

                  versionSt = line.split(GBCommon.VERSION_STR)[1].trim().split(" ")[0];

                } else if (line.startsWith(GBCommon.DEFINITION_STR)) {

                  definitionSt += line.split(GBCommon.DEFINITION_STR)[1].trim();
                  do {
                    line = reader.readLine();
                    if (line.startsWith(" ")) {
                      definitionSt += line.trim();
                    }
                  } while (line.startsWith(" "));
                  readLineFlag = false;

                } else if (line.startsWith(GBCommon.COMMENT_STR)) {

                  commentSt += line.split(GBCommon.COMMENT_STR)[1].trim();
                  do {
                    line = reader.readLine();
                    if (line.startsWith(" ")) {
                      commentSt += "\n" + line.trim();
                    }
                  } while (line.startsWith(" "));
                  readLineFlag = false;

                } else if (line.startsWith(GBCommon.FEATURES_STR)) {

                  do {
                    line = reader.readLine();

                    String lineSubstr5 = line.substring(5);

                    if (lineSubstr5.startsWith(GBCommon.CDS_STR)) {
                      String positionsSt = "";
                      positionsSt += line.trim().split(GBCommon.CDS_STR)[1].trim();

                      line = reader.readLine();

                      while (!line.trim().startsWith("/")) {
                        positionsSt += line.trim();
                        line = reader.readLine();
                      }

                      cdsList.add(positionsSt);

                    } else if (lineSubstr5.startsWith(GBCommon.GENE_STR)) {

                      String positionsSt = "";
                      positionsSt += line.trim().split(GBCommon.GENE_STR)[1].trim();

                      line = reader.readLine();

                      while (!line.trim().startsWith("/")) {
                        positionsSt += line.trim();
                        line = reader.readLine();
                      }

                      geneList.add(positionsSt);

                    } else if (lineSubstr5.startsWith(GBCommon.MISC_RNA_STR)) {

                      String positionsSt = "";
                      positionsSt += line.trim().split(GBCommon.MISC_RNA_STR)[1].trim();

                      line = reader.readLine();

                      while (!line.trim().startsWith("/")) {
                        positionsSt += line.trim();
                        line = reader.readLine();
                      }

                      miscRnaList.add(positionsSt);

                    } else if (lineSubstr5.startsWith(GBCommon.TM_RNA_STR)) {

                      String positionsSt = "";
                      positionsSt += line.trim().split(GBCommon.TM_RNA_STR)[1].trim();

                      line = reader.readLine();

                      while (!line.trim().startsWith("/")) {
                        positionsSt += line.trim();
                        line = reader.readLine();
                      }

                      tmRnaList.add(positionsSt);

                    } else if (lineSubstr5.startsWith(GBCommon.R_RNA_STR)) {

                      String positionsSt = "";
                      positionsSt += line.trim().split(GBCommon.R_RNA_STR)[1].trim();

                      line = reader.readLine();

                      while (!line.trim().startsWith("/")) {
                        positionsSt += line.trim();
                        line = reader.readLine();
                      }

                      rRnaList.add(positionsSt);

                    } else if (lineSubstr5.startsWith(GBCommon.M_RNA_STR)) {

                      String positionsSt = "";
                      positionsSt += line.trim().split(GBCommon.M_RNA_STR)[1].trim();

                      line = reader.readLine();

                      while (!line.trim().startsWith("/")) {
                        positionsSt += line.trim();
                        line = reader.readLine();
                      }

                      mRnaList.add(positionsSt);

                    } else if (lineSubstr5.startsWith(GBCommon.NC_RNA_STR)) {

                      String positionsSt = "";
                      positionsSt += line.trim().split(GBCommon.NC_RNA_STR)[1].trim();

                      line = reader.readLine();

                      while (!line.trim().startsWith("/")) {
                        positionsSt += line.trim();
                        line = reader.readLine();
                      }

                      ncRnaList.add(positionsSt);

                    } else if (lineSubstr5.startsWith(GBCommon.T_RNA_STR)) {

                      String positionsSt = "";
                      positionsSt += line.trim().split(GBCommon.T_RNA_STR)[1].trim();

                      line = reader.readLine();

                      while (!line.trim().startsWith("/")) {
                        positionsSt += line.trim();
                        line = reader.readLine();
                      }

                      tRnaList.add(positionsSt);
                    }

                  } while (line.startsWith(" "));
                  readLineFlag = false;

                } else if (line.startsWith(GBCommon.ORIGIN_STR)) {

                  originFound = true;

                  do {
                    line = reader.readLine();
                    String[] tempArray = line.trim().split(" ");
                    for (int i = 1; i < tempArray.length; i++) {
                      seqStBuilder.append(tempArray[i]);
                    }

                  } while (line.startsWith(" "));
                  readLineFlag = false;
                }

                if (readLineFlag) {
                  line = reader.readLine();
                }

              } while (line != null && !line.startsWith(GBCommon.LAST_LINE_STR));

              // --------create genome element node--------------
              long genomeElementId =
                  createGenomeElementNode(
                      versionSt,
                      commentSt,
                      definitionSt,
                      inserter,
                      genomeElementVersionIndex,
                      nodeTypeIndex);

              // -----------genes-----------------
              for (String genePositionsSt : geneList) {
                geneProperties.put(GeneNode.POSITIONS_PROPERTY, genePositionsSt);
                long geneId = inserter.createNode(geneProperties);
                inserter.createRelationship(genomeElementId, geneId, genomeElementGeneRel, null);

                // indexing gene node by its node_type
                nodeTypeIndex.add(
                    geneId, MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, GeneNode.NODE_TYPE));
              }

              // -----------CDS-----------------
              for (String cdsPositionsSt : cdsList) {
                cdsProperties.put(CDSNode.POSITIONS_PROPERTY, cdsPositionsSt);
                long cdsID = inserter.createNode(cdsProperties);
                inserter.createRelationship(genomeElementId, cdsID, genomeElementCDSRel, null);

                // indexing CDS node by its node_type
                nodeTypeIndex.add(
                    cdsID, MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, CDSNode.NODE_TYPE));
              }

              // -----------misc rna-----------------
              for (String miscRnaPositionsSt : miscRnaList) {
                miscRnaProperties.put(MiscRNANode.POSITIONS_PROPERTY, miscRnaPositionsSt);
                long miscRnaID = inserter.createNode(miscRnaProperties);
                inserter.createRelationship(
                    genomeElementId, miscRnaID, genomeElementMiscRnaRel, null);

                // indexing MiscRNA node by its node_type
                nodeTypeIndex.add(
                    miscRnaID,
                    MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, MiscRNANode.NODE_TYPE));
              }

              // -----------m rna-----------------
              for (String mRnaPositionsSt : mRnaList) {
                mRnaProperties.put(MRNANode.POSITIONS_PROPERTY, mRnaPositionsSt);
                long mRnaID = inserter.createNode(mRnaProperties);
                inserter.createRelationship(genomeElementId, mRnaID, genomeElementMRnaRel, null);

                // indexing MRNA node by its node_type
                nodeTypeIndex.add(
                    mRnaID, MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, MRNANode.NODE_TYPE));
              }

              // -----------nc rna-----------------
              for (String ncRnaPositionsSt : ncRnaList) {
                ncRnaProperties.put(NcRNANode.POSITIONS_PROPERTY, ncRnaPositionsSt);
                long ncRnaID = inserter.createNode(ncRnaProperties);
                inserter.createRelationship(genomeElementId, ncRnaID, genomeElementNcRnaRel, null);

                // indexing NCRNA node by its node_type
                nodeTypeIndex.add(
                    ncRnaID, MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, NcRNANode.NODE_TYPE));
              }

              // -----------r rna-----------------
              for (String rRnaPositionsSt : rRnaList) {
                rRnaProperties.put(RRNANode.POSITIONS_PROPERTY, rRnaPositionsSt);
                long rRnaID = inserter.createNode(rRnaProperties);
                inserter.createRelationship(genomeElementId, rRnaID, genomeElementRRnaRel, null);

                // indexing RRNA node by its node_type
                nodeTypeIndex.add(
                    rRnaID, MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, RRNANode.NODE_TYPE));
              }

              // -----------tm rna-----------------
              for (String tmRnaPositionsSt : tmRnaList) {
                tmRnaProperties.put(TmRNANode.POSITIONS_PROPERTY, tmRnaPositionsSt);
                long tmRnaID = inserter.createNode(tmRnaProperties);
                inserter.createRelationship(genomeElementId, tmRnaID, genomeElementTmRnaRel, null);

                // indexing TmRNA node by its node_type
                nodeTypeIndex.add(
                    tmRnaID, MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, TmRNANode.NODE_TYPE));
              }

              // -----------t rna-----------------
              for (String tRnaPositionsSt : tRnaList) {
                tRnaProperties.put(TRNANode.POSITIONS_PROPERTY, tRnaPositionsSt);
                long tRnaID = inserter.createNode(tRnaProperties);
                inserter.createRelationship(genomeElementId, tRnaID, genomeElementTRnaRel, null);

                // indexing TRNA node by its node_type
                nodeTypeIndex.add(
                    tRnaID, MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, TRNANode.NODE_TYPE));
              }

              logger.log(Level.INFO, (versionSt + " saved!"));
            }
          }
        }

      } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage());
        StackTraceElement[] trace = e.getStackTrace();
        for (StackTraceElement stackTraceElement : trace) {
          logger.log(Level.SEVERE, stackTraceElement.toString());
        }
      } finally {

        // shutdown, makes sure all changes are written to disk
        indexProvider.shutdown();
        inserter.shutdown();

        // closing logger file handler
        fh.close();
      }
    }
  }
 @Test(expected = RestResultException.class)
 public void testConvertMapToMapWithWrongType() {
   converter.convertToResultType(
       MapUtil.map("test", 1, "test2", 2), new TypeInformation(MapUtil.map("test", "0")));
 }
 @Test(expected = RestResultException.class)
 public void testConvertDifferentMapsWithWrongType() {
   Hashtable<String, String> table = new Hashtable<String, String>();
   table.put("testkey", "testvalue");
   converter.convertToResultType(table, new TypeInformation(MapUtil.map("test", 2)));
 }
 @Test
 public void testConvertFromEmptyMapToObject() {
   Object result = converter.convertToResultType(MapUtil.map(), new TypeInformation(String.class));
   assertNull(result);
 }
 @Test(expected = RestResultException.class)
 public void testConvertFromMapWithWrongTypeToObject() {
   converter.convertToResultType(MapUtil.map("test", 2), new TypeInformation(String.class));
 }
 @Test(expected = RestResultException.class)
 public void testConvertFromMapWithSameTypeAndMultipleElementsToObject() {
   converter.convertToResultType(
       MapUtil.map("test", "test", "test2", "test2"), new TypeInformation(String.class));
 }
  @Test
  public void shouldFindDepthOneConnectionsForVanGogh() {

    GraphDatabaseConnectionManager graphDatabaseConnectionManager =
        GraphDatabaseConnectionManagerFactory.getInstance(
            GraphDatabaseConnectionType.EMBEDDED_DATABASE);

    String vincentVanGogh = "Vincent van Gogh";
    String paulGauguin = "Paul Gauguin";
    String emileBernard = "Émile Bernard";

    try (GraphDatabaseTransaction tx = graphDatabaseConnectionManager.getTransactionManager()) {

      graphDatabaseConnectionManager.executeCypherQuery(
          "CREATE (:" + WikipediaLabel.Wikipedia + " {title: {title}})",
          MapUtil.map("title", vincentVanGogh));
      graphDatabaseConnectionManager.executeCypherQuery(
          "CREATE (:" + WikipediaLabel.Wikipedia + " {title: {title}})",
          MapUtil.map("title", paulGauguin));
      graphDatabaseConnectionManager.executeCypherQuery(
          "CREATE (:" + WikipediaLabel.Wikipedia + " {title: {title}})",
          MapUtil.map("title", emileBernard));

      graphDatabaseConnectionManager.executeCypherQuery(
          "MATCH (n:"
              + WikipediaLabel.Wikipedia
              + " {title: {title1}}), (m:"
              + WikipediaLabel.Wikipedia
              + " {title: {title2}}) CREATE (n)-[:"
              + WikipediaRelationship.REFERS
              + "]->(m)",
          MapUtil.map("title1", vincentVanGogh, "title2", paulGauguin));
      graphDatabaseConnectionManager.executeCypherQuery(
          "MATCH (n:"
              + WikipediaLabel.Wikipedia
              + " {title: {title1}}), (m:"
              + WikipediaLabel.Wikipedia
              + " {title: {title2}}) CREATE (n)-[:"
              + WikipediaRelationship.REFERS
              + "]->(m)",
          MapUtil.map("title1", vincentVanGogh, "title2", emileBernard));
      graphDatabaseConnectionManager.executeCypherQuery(
          "MATCH (n:"
              + WikipediaLabel.Wikipedia
              + " {title: {title1}}), (m:"
              + WikipediaLabel.Wikipedia
              + " {title: {title2}}) CREATE (n)-[:"
              + WikipediaRelationship.REFERS
              + "]->(m)",
          MapUtil.map("title1", paulGauguin, "title2", emileBernard));
      graphDatabaseConnectionManager.executeCypherQuery(
          "MATCH (n:"
              + WikipediaLabel.Wikipedia
              + " {title: {title1}}), (m:"
              + WikipediaLabel.Wikipedia
              + " {title: {title2}}) CREATE (n)-[:"
              + WikipediaRelationship.REFERS
              + "]->(m)",
          MapUtil.map("title1", emileBernard, "title2", paulGauguin));

      tx.success();
    }

    WikipediaSearchRepository wikipediaSearchRepository =
        new WikipediaSearchGraphDatabaseServiceRepository();

    WikipediaSearchResult wikipediaSearchResult =
        wikipediaSearchRepository.findDepthOneConnectionsByPageTitle(vincentVanGogh, false);

    List<WikipediaSearchResultNode> nodes = wikipediaSearchResult.getNodes();

    for (WikipediaSearchResultNode node : nodes) {

      System.out.println(node.getId() + ": " + node.getName());
    }

    Assert.assertEquals(3, nodes.size());

    List<WikipediaSearchResultRelationship> relationships =
        wikipediaSearchResult.getRelationships();

    for (WikipediaSearchResultRelationship relationship : relationships) {

      System.out.println(
          "("
              + relationship.getSource()
              + ")-[:"
              + relationship.getLinkName()
              + "]->("
              + relationship.getTarget()
              + ")");
    }

    Assert.assertEquals(2, relationships.size());

    graphDatabaseConnectionManager.close();
  }