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"); if (!db.getMetadata().getSchema().existsClass(CLASS)) { db.getMetadata().getSchema().createClass(CLASS);
@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; }
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; }
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();
switch (dbType) { case DOCUMENT: documentDatabase = new ODatabaseDocumentTx(dbURL); documentDatabase.open(dbUser, dbPassword); break; schemaClass = getOrCreateClass((String) cls.field("name"), (String) cls.field("extends")); Integer clusters = cls.field("clusters"); if (clusters != null) OClassImpl.addClusters(schemaClass, clusters); log(OETLProcessor.LOG_LEVELS.DEBUG, "%s: found %d %s in class '%s'", getName(), schemaClass.count(), getUnit(), className); log(OETLProcessor.LOG_LEVELS.DEBUG, "%s: found %d %s in class '%s'", getName(), schemaClass.count(), getUnit(), className); String idxName = (String) resolve(idx.field("name")); if (idxName != null) { index = documentDatabase.getMetadata().getIndexManager().getIndex(idxName); if (index != null) if (!cls.existsProperty(fieldNameParts[0])) { index = documentDatabase.getMetadata().getIndexManager().getIndex(idxName); if (index != 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; }
@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++;
@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; }
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 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(); }
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 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); } }
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); } }
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 OrientSingleInsertion(OrientGraph orientGraph, File resultsPath) { super(GraphDatabaseType.ORIENT_DB, resultsPath); this.orientGraph = orientGraph; this.index = this.orientGraph.getRawGraph().getMetadata().getIndexManager().getIndex("V.nodeId"); }
sqlQuery = new OSQLSynchQuery<ODocument>(lookup); else { index = pipeline.getDocumentDatabase().getMetadata().getIndexManager().getIndex(lookup); if (index == null) { log(OETLProcessor.LOG_LEVELS.DEBUG, "WARNING: index %s not found. Lookups could be really slow", lookup); final OType idxFieldType = index.getDefinition().getTypes()[0]; joinValue = OType.convert(joinValue, idxFieldType.getDefaultJavaType()); result = index.get(joinValue); } else { if (sqlQuery instanceof OSQLSynchQuery) ((OSQLSynchQuery) sqlQuery).resetPagination(); result = pipeline.getDocumentDatabase().query(sqlQuery, joinValue);
/** * {@inheritDoc} * Create a new class of OrientDB documents if necessary. Enforce specified schema over the document class. * */ @Override public void createSchema() throws GoraException { if (schemaExists()) { return; } try (ODatabaseDocumentTx schemaTx = connectionPool.acquire()) { schemaTx.activateOnCurrentThread(); OClass documentClass = schemaTx.getMetadata().getSchema().createClass(orientDBMapping.getDocumentClass()); documentClass.createProperty("_id", OType.getTypeByClass(super.getKeyClass())).createIndex(OClass.INDEX_TYPE.UNIQUE); for (String docField : orientDBMapping.getDocumentFields()) { documentClass.createProperty(docField, OType.valueOf(orientDBMapping.getDocumentFieldType(docField).name())); } schemaTx.getMetadata().getSchema().reload(); } catch (Exception e) { throw new GoraException(e); } }
/** * Runs a {@link BiConsumer} of {@link ODatabaseDocumentTx} and {@link OClass} * if the specified {@code className} exists. */ protected static void withDatabaseAndClass(final Provider<DatabaseInstance> databaseInstance, final String className, final BiConsumer<ODatabaseDocumentTx, OClass> consumer) { withDatabase(databaseInstance, db -> { if (db.getMetadata().getSchema().existsClass(className)) { consumer.accept(db, db.getMetadata().getSchema().getClass(className)); } }); }
@Override public void apply() throws Exception { withDatabaseAndClass(componentDatabaseInstance, BROWSE_NODE, (db, table) -> { db.getMetadata().getSchema().dropClass(BROWSE_NODE); }); withDatabaseAndClass(componentDatabaseInstance, ASSET, (db, table) -> { if (!table.existsProperty(AssetEntityAdapter.P_CREATED_BY)) { table.createProperty(AssetEntityAdapter.P_CREATED_BY, OType.STRING); } if (!table.existsProperty(AssetEntityAdapter.P_CREATED_BY_IP)) { table.createProperty(AssetEntityAdapter.P_CREATED_BY_IP, OType.STRING); } }); } }
public void register(final ODatabaseDocumentTx db, @Nullable final Runnable initializer) { checkNotNull(db); OSchema schema = db.getMetadata().getSchema(); OClass type = schema.getClass(typeName); if (type == null) { int clusters = getMinimumClusters(); type = clusters > 0 ? schema.createClass(typeName, clusters) : schema.createClass(typeName); defineType(db, type); log.debug("Created schema type '{}': properties={}, indexes={}", type, type.properties(), type.getIndexes() ); if (initializer != null) { log.debug("Running initializer: {}", initializer); initializer.run(); } } this.dbName = db.getName(); this.schemaType = type; if (sendEvents() && entityHook != null) { entityHook.enableEvents(this); } if (resolveConflicts() && conflictHook != null) { conflictHook.enableConflictResolution(this); if (!conflictHook.equals(db.getConflictStrategy())) { db.setConflictStrategy(conflictHook); } } }