Java Code Examples for com.orientechnologies.orient.core.sql.OCommandSQL

The following examples show how to use com.orientechnologies.orient.core.sql.OCommandSQL. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: light   Source File: AbstractRuleRule.java    License: Apache License 2.0 6 votes vote down vote up
public static void loadCompileCache() {
    String sql = "SELECT FROM Rule";
    Map<String, Object> compileMap = ServiceLocator.getInstance().getMemoryImage("compileMap");
    ConcurrentMap<String, String> cache = (ConcurrentMap<String, String>)compileMap.get("cache");
    if(cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<String, String>()
                .maximumWeightedCapacity(10000)
                .build();
        compileMap.put("cache", cache);
    }
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        for (Vertex rule : (Iterable<Vertex>) graph.command(new OCommandSQL(sql)).execute()) {
            cache.put((String) rule.getProperty("ruleClass"), (String) rule.getProperty("sourceCode"));
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example 2
private void markNpmRepositoriesWithoutV1SearchIndexing() {
  List<String> npmRepositoryNames;
  try (ODatabaseDocumentTx db = configDatabaseInstance.get().connect()) {
    npmRepositoryNames = db.<List<ODocument>>query(new OSQLSynchQuery<ODocument>(SELECT_NPM_REPOSITORIES)).stream()
        .map(d -> (String) d.field(P_REPOSITORY_NAME))
        .collect(toList());
  }
  if (!npmRepositoryNames.isEmpty()) {
    log.info("Marking existing npm repositories as not supporting v1 search ({}).", npmRepositoryNames);
    OCommandSQL updateBucketsCommand = new OCommandSQL(UPDATE_BUCKET_ATTRIBUTES);
    int updates;
    try (ODatabaseDocumentTx db = componentDatabaseInstance.get().connect()) {
      updates = db.command(updateBucketsCommand).execute(npmRepositoryNames);
    }
    log.info("Marked {} existing npm repositories as not supporting v1 search.", updates);
  }
}
 
Example 3
/**
 * Removes the {@link BrowseNode} associated with the given asset id.
 */
public void deleteAssetNode(final ODatabaseDocumentTx db, final EntityId assetId) {
  // a given asset will only appear once in the tree
  ODocument document = getFirst(
      db.command(new OCommandSQL(FIND_BY_ASSET)).execute(
          ImmutableMap.of(P_ASSET_ID, recordIdentity(assetId))), null);

  if (document != null) {
    if (document.containsField(P_COMPONENT_ID)) {
      // component still exists, just remove asset details
      document.removeField(P_ASSET_ID);
      document.save();
    }
    else {
      maybeDeleteParents(db, document.field(P_REPOSITORY_NAME), document.field(P_PARENT_PATH));
      document.delete();
    }
  }
}
 
Example 4
Source Project: nexus-public   Source File: AssetEntityAdapter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
Asset findByProperty(final ODatabaseDocumentTx db,
                     final String propName,
                     final Object propValue,
                     final Component component)
{
  checkNotNull(propName);
  checkNotNull(propValue);
  checkNotNull(component);

  Map<String, Object> parameters = ImmutableMap.of(
      "bucket", bucketEntityAdapter.recordIdentity(component.bucketId()),
      "component", componentEntityAdapter.recordIdentity(component),
      "propValue", propValue
  );
  String query = String.format(
      "select from %s where %s = :bucket and %s = :component and %s = :propValue",
      DB_CLASS, P_BUCKET, P_COMPONENT, propName
  );
  Iterable<ODocument> docs = db.command(new OCommandSQL(query)).execute(parameters);
  ODocument first = Iterables.getFirst(docs, null);
  return first != null ? readEntity(first) : null;
}
 
Example 5
Source Project: light   Source File: AbstractRuleRule.java    License: Apache License 2.0 6 votes vote down vote up
protected String getRuleMap(OrientGraph graph, String host) throws Exception {
    String sql = "SELECT FROM Rule";
    if(host != null) {
        sql = sql + " WHERE host = '" + host;
    }
    String json = null;
    try {
        Map<String, String> ruleMap = new HashMap<String, String> ();
        for (Vertex rule : (Iterable<Vertex>) graph.command(new OCommandSQL(sql)).execute()) {
            ruleMap.put((String) rule.getProperty("ruleClass"), (String) rule.getProperty("sourceCode"));
        }
        json = mapper.writeValueAsString(ruleMap);
    } catch (Exception e) {
        logger.error("Exception:", e);
        throw e;
    } finally {
        graph.shutdown();
    }
    return json;
}
 
Example 6
private Iterable<T> browseByQuery(final ODatabaseDocumentTx db,
                                  @Nullable final String whereClause,
                                  @Nullable final Map<String, Object> parameters,
                                  @Nullable final Iterable<Bucket> buckets,
                                  @Nullable final String querySuffix,
                                  final boolean async)
{
  String query = buildQuery(false, whereClause, buckets, querySuffix);

  if (isBlank(query)) {
    log.debug("Skipped finding {}s as query is empty, parameters: {}", getTypeName(), parameters);
    return Collections.emptyList();
  }

  log.debug("Finding {}s with query: {}, parameters: {}", getTypeName(), query, parameters);

  if (async) {
    return transform(OrientAsyncHelper.asyncIterable(db, query, parameters));
  }
  else {
    Iterable<ODocument> docs = db.command(new OCommandSQL(query)).execute(parameters);
    return transform(docs);
  }
}
 
Example 7
long countByQuery(final ODatabaseDocumentTx db,
                  @Nullable final String whereClause,
                  @Nullable final Map<String, Object> parameters,
                  @Nullable final Iterable<Bucket> buckets,
                  @Nullable final String querySuffix)
{
  String query = buildQuery(true, whereClause, buckets, querySuffix);

  if (isBlank(query)) {
    log.debug("Skipped counting {}s as query is empty, parameters: {}", getTypeName(), parameters);
    return 0;
  }

  log.debug("Counting {}s with query: {}, parameters: {}", getTypeName(), query, parameters);
  List<ODocument> results = db.command(new OCommandSQL(query)).execute(parameters);
  return results.get(0).field("count");
}
 
Example 8
long countGroupByQuery(final ODatabaseDocumentTx db,
                       @Nullable final String whereClause,
                       @Nullable final Map<String, Object> parameters,
                       @Nullable final Iterable<Bucket> buckets,
                       final String querySuffix)
{
  checkNotNull(querySuffix);
  checkState(containsIgnoreCase(querySuffix, "group by"));

  String query = buildQuery(true, whereClause, buckets, querySuffix);

  if (isBlank(query)) {
    log.debug("Skipped counting {}s as query is empty, parameters: {}", getTypeName(), parameters);
    return 0;
  }

  query = "select count(*) from (" + buildQuery(true, whereClause, buckets, querySuffix) + ")";

  log.debug("Counting {}s with grouped by query: {}, parameters: {}", getTypeName(), query, parameters);
  List<ODocument> results = db.command(new OCommandSQL(query)).execute(parameters);
  return results.get(0).field("count");
}
 
Example 9
@Override
public void apply() {
  withDatabaseAndClass(securityDatabaseInstance, DB_CLASS, (db, type) -> {
    List<ODocument> results = db.command(new OCommandSQL(QUERY)).execute();
    results.forEach(result -> {
      Map<String, String> properties = result.field(P_PROPERTIES, OType.EMBEDDEDMAP);
      if (properties != null) {
        String actionString = properties.get(P_ACTIONS);
        if (actionString != null) {
          List<String> actions = new ArrayList(Arrays.asList(actionString.split(",")));
          if (actions.contains("add") || actions.contains("mark")) {
            actions.remove("add");
            actions.remove("mark");
            if (!actions.contains("create")) {
              actions.add("create");
            }
            properties.put(P_ACTIONS, String.join(",", actions));
            result.field(P_PROPERTIES, properties);
            log.info("Updated application privilege {} to align with CRUD actions", (String) result.field(P_NAME));
            result.save();
          }
        }
      }
    });
  });
}
 
Example 10
@Test
public void testApply() {
  try (ODatabaseDocumentTx securityDb = securityDatabase.getInstance().connect()) {
    createPrivilege("a_test_priv", "read,edit,delete,add");
    createPrivilege("b_test_priv", "mark,read,edit,delete");
    createPrivilege("c_test_priv", "create,read,edit,delete,add");
    createPrivilege("d_test_priv", "mark,read,edit,delete,create");
  }

  underTest.apply();

  try (ODatabaseDocumentTx securityDb = securityDatabase.getInstance().connect()) {
    List<ODocument> result = securityDb.command(new OCommandSQL("select from privilege")).execute();
    assertThat(result.size(), is(4));
    assertThat(result.get(0).field(P_NAME), is("a_test_priv"));
    assertThat(result.get(0).field(P_PROPERTIES), hasEntry(is("actions"), is("read,edit,delete,create")));
    assertThat(result.get(1).field(P_NAME), is("b_test_priv"));
    assertThat(result.get(1).field(P_PROPERTIES), hasEntry(is("actions"), is("read,edit,delete,create")));
    assertThat(result.get(2).field(P_NAME), is("c_test_priv"));
    assertThat(result.get(2).field(P_PROPERTIES), hasEntry(is("actions"), is("create,read,edit,delete")));
    assertThat(result.get(3).field(P_NAME), is("d_test_priv"));
    assertThat(result.get(3).field(P_PROPERTIES), hasEntry(is("actions"), is("read,edit,delete,create")));
  }
}
 
Example 11
Source Project: orientdb-lucene   Source File: LuceneMixIndexTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void init() {

  initDB();
  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  OClass v = schema.getClass("V");
  OClass song = schema.createClass("Song");
  song.setSuperClass(v);
  song.createProperty("title", OType.STRING);
  song.createProperty("author", OType.STRING);
  song.createProperty("lyrics", OType.STRING);

  databaseDocumentTx.command(new OCommandSQL("create index Song.author on Song (author) NOTUNIQUE")).execute();

  databaseDocumentTx.command(new OCommandSQL("create index Song.composite on Song (title,lyrics) FULLTEXT ENGINE LUCENE"))
      .execute();

  InputStream stream = ClassLoader.getSystemResourceAsStream("testLuceneIndex.sql");

  databaseDocumentTx.command(new OCommandScript("sql", getScriptFromStream(stream))).execute();

}
 
Example 12
Source Project: orientdb-lucene   Source File: LuceneFacetTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void init() {
  initDB();
  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  OClass oClass = schema.createClass("Item");

  oClass.createProperty("name", OType.STRING);
  oClass.createProperty("category", OType.STRING);

  databaseDocumentTx
      .command(
          new OCommandSQL(
              "create index Item.name_category on Item (name,category) FULLTEXT ENGINE LUCENE METADATA { 'facetFields' : ['category']}"))
      .execute();

}
 
Example 13
Source Project: orientdb-lucene   Source File: LuceneListIndexing.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void init() {
  initDB();

  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  OClass oClass = schema.createClass("City");

  OClass person = schema.createClass("Person");

  person.createProperty("name", OType.STRING);
  person.createProperty("tags", OType.EMBEDDEDLIST, OType.STRING);

  oClass.createProperty("name", OType.STRING);
  oClass.createProperty("tags", OType.EMBEDDEDLIST, OType.STRING);

  databaseDocumentTx.command(new OCommandSQL("create index City.tags on City (tags) FULLTEXT ENGINE LUCENE")).execute();

  databaseDocumentTx.command(new OCommandSQL("create index Person.name_tags on Person (name,tags) FULLTEXT ENGINE LUCENE"))
      .execute();
}
 
Example 14
Source Project: Orienteer   Source File: OTaskSession.java    License: Apache License 2.0 6 votes vote down vote up
public void atomicChange(final String field, final Object value,final String changeCommand){
	new DBClosure<Boolean>() {
		@Override
		protected Boolean execute(ODatabaseDocument db) {
			int maxRetries = 50;
			OCommandSQL command = new OCommandSQL("update "+document.getIdentity()+" "+changeCommand);
			int retry = 0;					
			while(true){
				try {
					command.execute(value);
					break;
				} catch (OConcurrentModificationException  e) {
					retry++;
					try { Thread.sleep((long) (Math.random()*150));} catch (InterruptedException e1) {}
					if (retry>=maxRetries){
						throw e;//if all retries failed
					}
				}
			}
			document.reload();
			return true;
		}
	}.execute();
}
 
Example 15
Source Project: light   Source File: AbstractPageRule.java    License: Apache License 2.0 5 votes vote down vote up
protected String getPageMap(OrientGraph graph, String host) throws Exception {
    String sql = "SELECT FROM Page";
    if(host != null) {
        sql = sql + " WHERE host = '" + host + "' OR host IS NULL";
    }
    Map<String, String> map = new HashMap<String, String>();
    for (Vertex page : (Iterable<Vertex>) graph.command(new OCommandSQL(sql)).execute()) {
        map.put(page.getProperty("pageId"), page.getProperty("content"));
    }
    return mapper.writeValueAsString(map);
}
 
Example 16
Source Project: nexus-repository-p2   Source File: P2Upgrade_1_1.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void updateP2BrowseNodes(final List<String> p2RepositoryNames) {
  log.info("Deleting browse_node data from p2 repositories to be rebuilt ({}).", p2RepositoryNames);

  DatabaseUpgradeSupport.withDatabaseAndClass(componentDatabaseInstance, C_BROWSE_NODE, (db, type) -> {
    OSchemaProxy schema = db.getMetadata().getSchema();
    if (schema.existsClass(C_BROWSE_NODE)) {
      db.command(new OCommandSQL(DELETE_BROWSE_NODE_FROM_REPOSITORIES)).execute(p2RepositoryNames);
    }
  });
}
 
Example 17
Source Project: Orienteer   Source File: AbstractEntityHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void delete(T entity, OPersistenceSession session) {
	ODatabaseDocument db = session.getDatabase();
	String id = entity.getId();
	String oid = (String) convertValueFromEntity("id", id);
	OIdentifiable oIdentifiable = session.lookupOIdentifiableForIdInCache(oid);
	if(oIdentifiable!=null) {
		db.delete(oIdentifiable.getIdentity());
	} else {
		db.command(new OCommandSQL("delete from "+getSchemaClass()+" where "+getPkField()+" = ?")).execute(oid);
	}
}
 
Example 18
Source Project: light   Source File: AbstractFormRule.java    License: Apache License 2.0 5 votes vote down vote up
protected String getFormMap(String host) throws Exception {
    String sql = "SELECT FROM Form";
    if(host != null) {
        sql = sql + " WHERE host = '" + host + "' OR host IS NULL";
    }
    String json = null;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        Map<String, Map<String, Object>> formMap = new HashMap<String, Map<String, Object>>();
        for (Vertex v : (Iterable<Vertex>) graph.command(
                new OCommandSQL(sql)).execute()) {
            Map<String, Object> contentMap = new HashMap<String, Object>();
            contentMap.put("action", v.getProperty("action"));
            contentMap.put("schema", v.getProperty("schema"));
            contentMap.put("form", v.getProperty("form"));
            contentMap.put("modelData", v.getProperty("modelData"));
            formMap.put(v.getProperty("formId"), contentMap);
        }
        json = mapper.writeValueAsString(formMap);
    } catch (Exception e) {
        logger.error("Exception:", e);
        throw e;
    } finally {
        graph.shutdown();
    }
    return json;
}
 
Example 19
@Override
public List<String> findAssetPaths(final String repositoryName) {
  String sql = "SELECT * FROM asset WHERE bucket.repository_name = ?";
  try (ODatabaseDocumentTx tx = databaseInstanceProvider.get().acquire()) {
    tx.begin();
    List<ODocument> results = tx.command(new OCommandSQL(sql)).execute(repositoryName);
    return results.stream().map(doc -> doc.field("name", String.class).toString()).collect(toList());
  }
}
 
Example 20
private void executeSqlStatements(final String... sqlStatements) {
  try (ODatabaseDocumentTx db = componentDb.get().connect()) {
    for (String sqlStatement : sqlStatements) {
      db.command(new OCommandSQL(sqlStatement)).execute();
    }
  }
}
 
Example 21
Source Project: nexus-public   Source File: PypiUpgrade_1_1.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void deleteIndexes() {
  List<String> pypiRepositoryNames;
  try (ODatabaseDocumentTx db = configDatabaseInstance.get().connect()) {
    pypiRepositoryNames = db.<List<ODocument>>query(new OSQLSynchQuery<ODocument>(SELECT_PYPI_REPOSITORIES)).stream()
        .map(d -> (String) d.field(P_REPOSITORY_NAME))
        .collect(Collectors.toList());
  }

  if (!pypiRepositoryNames.isEmpty()) {
    OCommandSQL deleteIndexCommand = new OCommandSQL(DELETE_INDEXES);
    OCommandSQL deleteBrowseNodesCommand = new OCommandSQL(DELETE_BROWSE_NODES);
    try (ODatabaseDocumentTx db = componentDatabaseInstance.get().connect()) {
      OIndex<?> bucketIdx = db.getMetadata().getIndexManager().getIndex(I_REPOSITORY_NAME);
      pypiRepositoryNames.forEach(repositoryName -> {
        log.info("Scanning pypi repository {} for index file assets", repositoryName);
        OIdentifiable bucket = (OIdentifiable) bucketIdx.get(repositoryName);
        if (bucket == null) {
          log.warn("Unable to find bucket for {}", repositoryName);
        }
        else {
          // Deleting index files
          int deletes = db.command(deleteIndexCommand).execute(bucket.getIdentity());
          if (deletes > 0) {
            log.info(
                "Deleted {} pypi index asset(s) in repository {}: ", deletes, repositoryName);
          }

          if (db.getMetadata().getSchema().existsClass(BROWSE_NODE_CLASS)) {
            // Deleting browse nodes
            deletes = db.command(deleteBrowseNodesCommand).execute(repositoryName);
            if (deletes > 0) {
              log.info(
                  "Deleted {} browse node(s) in repository {}", deletes, repositoryName);
            }
          }
        }
      });
    }
  }
}
 
Example 22
Source Project: nexus-public   Source File: MavenUpgrade_1_1.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void updateMavenIndexFileAssetKind() {
  List<String> mavenRepositoryNames;
  try (ODatabaseDocumentTx db = configDatabaseInstance.get().connect()) {
    mavenRepositoryNames = db.<List<ODocument>>query(new OSQLSynchQuery<ODocument>(SELECT_MAVEN_REPOSITORIES)).stream()
        .map(d -> (String)d.field(P_REPOSITORY_NAME))
        .collect(Collectors.toList());
  }
  if (!mavenRepositoryNames.isEmpty()) {
    OCommandSQL updateAssetCommand = new OCommandSQL(UPDATE_ASSET_KIND);
    try (ODatabaseDocumentTx db = componentDatabaseInstance.get().connect()) {
      OIndex<?> bucketIdx = db.getMetadata().getIndexManager().getIndex(I_REPOSITORY_NAME);
      mavenRepositoryNames.forEach(repositoryName -> {
        log.info("Scanning maven2 repository {} for maven index file assets", repositoryName);
        OIdentifiable bucket = (OIdentifiable) bucketIdx.get(repositoryName);
        if (bucket == null) {
          log.warn("Unable to find bucket for {}", repositoryName);
        }
        else {
          int updates = db.command(updateAssetCommand).execute(bucket.getIdentity());
          if (updates > 0) {
            log.info(
                "Updated {} maven index file asset(s) in repository {}: " +
                    "set attributes.maven2.asset_kind='REPOSITORY_INDEX'", updates, repositoryName);
          }
        }
      });
    }
  }
}
 
Example 23
Source Project: nexus-public   Source File: EntityAdapter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public Iterable<ODocument> documents(final ODatabaseDocumentTx db, final Iterable<EntityId> ids) {
  Set<ORID> rids = stream(ids).map(id -> {
    if (id instanceof AttachedEntityId) {
      return ((AttachedEntityId) id).getIdentity();
    }
    return getRecordIdObfuscator().decode(getSchemaType(), id.getValue());
  }).collect(toSet());

  return db.command(new OCommandSQL("select from :rids")).execute(singletonMap("rids", rids));
}
 
Example 24
public boolean execute(final ODatabaseDocumentTx db, final Object... values) {
  checkNotNull(db);
  checkArgument(values.length > 0);

  int records = db.command(new OCommandSQL(query))
      .execute(values);

  return records == 1;
}
 
Example 25
public boolean exists(final ODatabaseDocumentTx db, final String name) {
  checkNotNull(db);
  checkNotNull(name);

  ImmutableMap<String, String> parameters = ImmutableMap.of("name", name.toUpperCase());
  StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM " + DB_CLASS + " WHERE (name.toUpperCase() = :name)");

  log.debug("Counting {}s with query: {}, parameters: {}", getTypeName(), query, parameters);

  List<ODocument> result = db.command(new OCommandSQL(query.toString())).execute(parameters);
  return ((long) result.get(0).field("COUNT")) != 0L;
}
 
Example 26
private Iterable<ODocument> buildAndRunQuery(final ODatabaseDocumentTx db,
                                             final String whereClause,
                                             final Map<String, String> parameters)
{
  StringBuilder query = new StringBuilder("SELECT FROM " + DB_CLASS + whereClause);
  log.debug("Finding {}s with query: {}, parameters: {}", getTypeName(), query, parameters);
  return db.command(new OCommandSQL(query.toString())).execute(parameters);
}
 
Example 27
@Override
public void apply() {
  try (ODatabaseDocumentTx db = databaseInstance.get().connect()) {

    getRepositoriesWithACleanupPolicy(db).forEach(repository -> {
      db.command(new OCommandSQL(
          format(UPDATE_REPOSITORY,
              repository.field(ATTRIBUTES_CLEANUP_POLICY_NAME),
              repository.field(RID))))
          .execute();
    });
  }
}
 
Example 28
private void renameAssetLastAccessedField() {
  try (ODatabaseDocumentTx db = componentDatabaseInstance.get().connect()) {
    OClass assetClass = getAssetDbClass(db);
    if (assetClass.existsProperty(P_LAST_ACCESSED)) {
      db.command(new OCommandSQL(ALTER_ASSET_LAST_ACCESSED)).execute();
    }
  }
}
 
Example 29
@Override
public void apply() throws Exception {
  try (ODatabaseDocumentTx db = componentDatabaseInstance.get().connect()) {
    if(db.getMetadata().getSchema().existsClass("assetdownloadcount")){
      int updates = db.command(new OCommandSQL(UPDATE_ASSET_NAME)).execute();
      if (updates > 0) {
        log.info("Updated {} records with null assetIds", updates);
      }
    }
  }
}
 
Example 30
/**
 * Returns the {@link BrowseNode} with the same coordinates as the sample node; {@code null} if no such node exists.
 */
@Nullable
private static ODocument findNodeRecord(final ODatabaseDocumentTx db, final OrientBrowseNode node) {
  return getFirst(
      db.command(new OCommandSQL(FIND_BY_PARENT_PATH)).execute(
          ImmutableMap.of(
              P_REPOSITORY_NAME, node.getRepositoryName(),
              P_PARENT_PATH, node.getParentPath(),
              P_NAME, node.getName())),
      null);
}