private void executeCommand(String query, Object... args) { activateOnCurrentThread(); db.command(new OCommandSQL(query)).execute(args); }
@Override public Status insert(String table, String key, Map<String, ByteIterator> values) { try (ODatabaseDocumentTx db = databasePool.acquire()) { final ODocument document = new ODocument(CLASS); for (Map.Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { document.field(entry.getKey(), entry.getValue()); } document.save(); final ODictionary<ORecord> dictionary = db.getMetadata().getIndexManager().getDictionary(); dictionary.put(key, document); return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; }
ODatabaseDocumentTx db = new ODatabaseDocumentTx(url); if (db.getStorage().isRemote()) { isRemote = true; if (!isRemote) { if (newdb) { if (db.exists()) { db.open(user, password); LOG.info("OrientDB drop and recreate fresh db"); db.drop(); db.create(); } else { if (!db.exists()) { LOG.info("OrientDB database not found, creating fresh db"); db.create(); server.createDatabase(db.getName(), ORIENTDB_DOCUMENT_TYPE, remoteStorageType); } else { if (!server.existsDatabase()) { if (db.isClosed()) { db.open(user, password); if (!db.getMetadata().getSchema().existsClass(CLASS)) { db.getMetadata().getSchema().createClass(CLASS);
public final void updateSchema() { if (db.isClosed()) { db.create(); } OSchema schema = db.getMetadata().getSchema(); for (String docType : DocumentTypes.getDocumentTypes()) { if (!schema.existsClass(docType)) { createDocType(schema, docType); } } if (!schema.existsClass("Signatures")) { createSignatureType(schema); } }
public long getCount(final ODatabaseDocumentTx db, final String repositoryName, final String assetName) { checkNotNull(db); checkNotNull(repositoryName); checkNotNull(assetName); Map<String, Object> parameters = buildQueryParameters(repositoryName, assetName, DateType.DAY, null, null); Iterable<ODocument> docs = db.command(new OCommandSQL(TOTAL_COUNT_QUERY)).execute(parameters); ODocument result = Iterables.getFirst(docs, null); if (result != null) { return result.field("sum", OType.LONG); } return 0; }
protected ODocument getODocumentByHostId(OrientGraph graph, String index, String host, String id) { ODocument doc = null; OIndex<?> hostIdIdx = graph.getRawGraph().getMetadata().getIndexManager().getIndex(index); // this is a unique index, so it retrieves a OIdentifiable OCompositeKey key = new OCompositeKey(host, id); OIdentifiable oid = (OIdentifiable) hostIdIdx.get(key); if (oid != null) { doc = (ODocument)oid.getRecord(); } return doc; }
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); } } }); } } } }
@Override public void init() { try (ODatabaseDocumentTx db = docDb()) { OSchema schema = db.getMetadata().getSchema(); if (!schema.existsClass(GCP_CONFIG)) { OClass newClass = schema.createClass(GCP_CONFIG); newClass.createProperty("hg", OType.STRING); newClass.createProperty("map", OType.EMBEDDEDMAP); newClass.createIndex("hg.unq", OClass.INDEX_TYPE.UNIQUE, "hg"); db.commit(true); db.command(new OCommandSQL("INSERT INTO " + GCP_CONFIG + " SET hg=\"" + hostGroup + "\", map={}")).execute(); } fetchFromDb(db); executor.scheduleAtFixedRate(() -> { LOG.info("Trying to reload configuration from main DB."); putLock.writeLock().lock(); try { if (!isClosed) { try (ODatabaseDocumentTx _db = docDb()) { fetchFromDb(_db); } } } finally { putLock.writeLock().unlock(); } }, readLong(ConfigProperty.POLL_INTERVAL), readLong(ConfigProperty.POLL_INTERVAL), TimeUnit.MILLISECONDS); } }
if (db.getMetadata().getSchema().existsClass("Config")) { List<ODocument> list = db.command(query).execute(); ODocument doc = list.get(0); try { // try to parse int version = Integer.parseInt((String) doc.field("value", String.class)); } catch (Throwable e) { logger.warn("getConfigVersion could not determine correct version although Config class exists in database", e); db.close();
@Override public String getValue(String key) { OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>("select * from Config where key = ?"); List<ODocument> result = db.command(query).execute(key); // not found? if (result == null || result.isEmpty()) return null; // otherwise get document ODocument config = result.get(0); // and return value return config.field("value", String.class); }
@Override public void apply() throws Exception { try (ODatabaseDocumentTx db = databaseInstance.get().connect()) { OSchema schema = db.getMetadata().getSchema(); OClass type = schema.getClass("audit_data"); if (type != null) { int[] clusterIds = type.getClusterIds(); if (clusterIds.length > 1) { type.setDefaultClusterId(primaryClusterId); log.info("Moving events to primary cluster {}", db.getClusterNameById(primaryClusterId)); for (ODocument document : db.browseClass(type.getName())) { ORID rid = document.getIdentity(); if (rid.getClusterId() != primaryClusterId) { db.save(new ODocument(document.toStream())); db.delete(rid); moveCount++; log.info("Dropping secondary cluster {}", db.getClusterNameById(clusterId)); db.dropCluster(clusterId, false);
@Override public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { try (ODatabaseDocumentTx db = databasePool.acquire()) { final ODictionary<ORecord> dictionary = db.getMetadata().getIndexManager().getDictionary(); final ODocument document = dictionary.get(key); if (document != null) { if (fields != null) { for (String field : fields) { result.put(field, new StringByteIterator((String) document.field(field))); } } else { for (String field : document.fieldNames()) { result.put(field, new StringByteIterator((String) document.field(field))); } } return Status.OK; } } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; }
@Override public void onAfterServerStartupAndActivation(OrientDbWebApplication app) throws Exception { IOrientDbSettings settings = app.getOrientDbSettings(); ODatabaseDocumentTx db = new ODatabaseDocumentTx(settings.getDBUrl()); if(!db.exists()) { db = db.create(); onDbCreated(db, settings); } if(db.isClosed()) db.open(settings.getAdminUserName(), settings.getAdminPassword()); db.getMetadata().load(); db.close(); }
@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); } } } } }
public OIndex build(final ODatabaseDocumentTx db) { checkState(!propertyNames.isEmpty(), "At least one property is required"); checkState(propertyTypes.size() == propertyNames.size(), "A type must be defined for each property"); List<OCollate> collates = null; if (caseInsensitive) { collates = Lists.transform(propertyNames, n -> new OCaseInsensitiveCollate()); } ODocument metadata = new ODocument(); if (ignoreNullValues) { metadata.field("ignoreNullValues", true); } OIndexDefinition indexDefinition = OIndexDefinitionFactory.createIndexDefinition(type, propertyNames, propertyTypes, collates, indexType.name(), null); return db.getMetadata().getIndexManager().createIndex(name, indexType.name(), indexDefinition, type.getPolymorphicClusterIds(), null, metadata.fields() > 0 ? metadata : null); } }
@Override public ILocation convertToEntity(ODocument document) { Location location = new Location(); location.setLongitude(document.field("longitude", Double.class)); location.setLatitude(document.field("latitude", Double.class)); location.setComment(document.field("comment", String.class)); // populate with data populateEntityWithBaseData(document, location); populateEntityWithCreatedModified(document, location); // parent ORecordId parent = document.field("parent", ORecordId.class); if (parent != null) { initDb(); location.setParentId(parent.getIdentity().toString()); location.setParentModel(db.getMetadata().getSchema().getClassByClusterId(parent.getClusterId()).getName()); //TODO: lazy load parent } // add distance, if set in document (added by some query results) if (document.field("$distance") != null) location.setDistance(document.field("$distance", Double.class)); return location; }
/** * Get a document by sourceUri and update it from the given map. * @param incomingDocMap The document's db columns. * @return The saved document. * @throws IllegalArgumentException if sourceUri or docType are null, or if the document doesn't exist. */ public ODocument mergeDocument(Map<String, ? extends Object> incomingDocMap) { String sourceUri = (String) incomingDocMap.get(DocumentAttributes.SOURCE_URI.toString()); if (null == sourceUri) throw new IllegalArgumentException("Document sourceUri is null."); String docType = (String) incomingDocMap.get(Crawler.Attributes.TYPE); if (null == docType) throw new IllegalArgumentException("Document docType is null."); // Get a document by sourceUri String sql = "SELECT * FROM " + docType + " WHERE sourceuri=?"; activateOnCurrentThread(); List<ODocument> results = db.command(new OSQLSynchQuery<ODocument>(sql)).execute(sourceUri); if (results.size() == 0) throw new JBakeException("No document with sourceUri '"+sourceUri+"'."); // Update it from the given map. ODocument incomingDoc = new ODocument(docType); incomingDoc.fromMap(incomingDocMap); ODocument merged = results.get(0).merge(incomingDoc, true, false); return merged; }
@Override public void deleteByRelation(INode node) { // delete source reference pointing to relation node OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>("select * from Relation where relationLink.in = " + node.getId() + " OR relationLink.out = " + node.getId()); List<ODocument> result = db.command(query).execute(); // remove relation and link for (ODocument document : result) { ODocument relationLink = getRelationLink(document, true); if (relationLink != null && db.load(relationLink.getIdentity()) != null) relationLink.delete(); document.delete(); } }
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(); } } }
private void createComponentIndex(final ODatabaseDocumentTx db, final OClass type) { if (db.getMetadata().getIndexManager().getIndex(I_COMPONENT) == null) { type.createIndex(I_COMPONENT, INDEX_TYPE.NOTUNIQUE, AssetEntityAdapter.P_COMPONENT); } }