@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; }
@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; }
/** * 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; }
@Test public void testRemovingReadonlyField2() { ODatabaseDocument db = wicket.getTester().getDatabase(); OSchema schema = db.getMetadata().getSchema(); OClass classA = schema.createClass("TestRemovingField2"); classA.createProperty("name", OType.STRING); OProperty property = classA.createProperty("property", OType.STRING); property.setReadonly(true); ODocument doc = new ODocument(classA); doc.field("name", "My Name"); doc.field("property", "value1"); doc.save(); doc.field("name", "My Name 2"); doc.field("property", "value2"); doc.undo(); doc.field("name", "My Name 3"); doc.save(); }
final OCommandSQL cmd = (OCommandSQL) fieldValue; cmd.getContext().setParent(iContext); fieldValue = ODatabaseRecordThreadLocal.instance().get().command(cmd).execute(); final OProperty prop = immutableClass.getProperty(fieldName); if (prop != null) { if (prop.getType() == OType.LINK) { if (OMultiValue.isMultiValue(fieldValue)) { final int size = OMultiValue.getSize(fieldValue); if (o instanceof OIdentifiable && !((OIdentifiable) o).getIdentity().isPersistent()) { final ORecord rec = ((OIdentifiable) o).getRecord(); if (rec != null && rec instanceof ODocument) { if (doc.fields() == 1) { singleFieldName = doc.fieldNames()[0]; tempColl.add(doc.field(singleFieldName)); } else { doc.getIdentity().reset(); ODocumentInternal.addOwner(doc, iDocument); ODocumentInternal.addOwner(doc, iDocument); iDocument.field(fieldName, resolveFieldValue(iDocument, fieldName, fieldValue, iArguments, iContext));
@Test public void testGettingFields() { OSchema schema = wicket.getTester().getSchema(); OClass classA = schema.createClass("GettingFields"); classA.createProperty("title", OType.STRING); classA.createProperty("link", OType.LINK).setLinkedClass(classA); classA.createProperty("multi", OType.LINKLIST).setLinkedClass(classA); ODocument doc = new ODocument(classA); doc.field("title", "test"); doc.save(); doc.field("link", doc); doc.field("multi", Arrays.asList(doc)); doc.save(); doc.reload(); String title = doc.field("title"); ODocument link = doc.field("link"); Collection<ODocument> multi = doc.field("multi"); }
private static List<String> checkRecord(final Set<ORID> iSourceRIDs, final OIdentifiable value, final ORecord iRootObject, String prefix) { List<String> result = new ArrayList<>(); if (iSourceRIDs.contains(value.getIdentity())) { result.add(prefix); } else if (!value.getIdentity().isValid() && value.getRecord() instanceof ODocument) { //embedded document ODocument doc = value.getRecord(); for (String fieldName : doc.fieldNames()) { Object fieldValue = doc.field(fieldName); result.addAll(checkObject(iSourceRIDs, fieldValue, iRootObject, prefix + "." + fieldName)); } } return result; }
ODocument doc = new ODocument(documentType); doc.fromMap(fileContents); boolean cached = fileContents.get(String.valueOf(DocumentAttributes.CACHED)) != null ? Boolean.valueOf((String) fileContents.get(String.valueOf(DocumentAttributes.CACHED))) : true; doc.field(String.valueOf(DocumentAttributes.CACHED), cached); doc.save(); } else { LOGGER.warn("{} has an invalid header, it has been ignored!", sourceFile);
@Before public void init() { doc = DBClosure.sudo(db -> { OSchema schema = db.getMetadata().getSchema(); OClass test = schema.createClass("Customer"); test.createProperty("name", OType.STRING); test.createProperty("phone", OType.STRING); ODocument document = new ODocument("Customer"); document.field("name", "Test Name"); document.save(); return document; }); }
protected void validateEmbedded(final IValidatable<T> validatable, final OProperty p, final Object fieldValue) { if (fieldValue instanceof ORecordId) { validatable.error(newValidationError("embeddedRecord")); return; } else if (fieldValue instanceof OIdentifiable) { if (((OIdentifiable) fieldValue).getIdentity().isValid()) { validatable.error(newValidationError("embeddedRecord")); return; } final OClass embeddedClass = p.getLinkedClass(); if (embeddedClass != null) { final ORecord rec = ((OIdentifiable) fieldValue).getRecord(); if (!(rec instanceof ODocument)) { validatable.error(newValidationError("embeddedNotDoc")); return; } final ODocument doc = (ODocument) rec; if (doc.getSchemaClass() == null || !(doc.getSchemaClass().isSubClassOf(embeddedClass))) { validatable.error(newValidationError("embeddedWrongType", "expectedType", embeddedClass.getName())); return; } } } else { validatable.error(newValidationError("embeddedNotDoc")); return; } }
@Test public void testOQueryModelDBTouch() { OClass classA = wicket.getTester().getSchema().getClass("ClassA"); ODocument doc = new ODocument(classA); doc.field("other", Arrays.asList(doc)); OQueryModel<ODocument> queryModel = new OQueryModel<ODocument>("select from ClassA where :doc in other"); queryModel.setParameter("doc", new ODocumentModel(doc)); long was = classA.count(); assertTrue(doc.getIdentity().isNew()); assertEquals(0, queryModel.size()); assertTrue(doc.getIdentity().isNew()); assertEquals(was, classA.count()); }
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 setValue(Object object, Object value, PropertyResolverConverter converter) { ODocument doc = toODocument(object); if(value!=null && ! OType.isSimpleType(value)) { //Try to convert if type is not simple OClass schemaClass = doc.getSchemaClass(); OProperty property = schemaClass.getProperty(exp); if(property!=null) { value = converter.convert(value, property.getType().getDefaultJavaType()); } } doc.field(exp, value); }
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); } }
@SuppressWarnings("unchecked") public OIdentifiable process() { while (target.hasNext()) { record = target.next(); index++; final ORecord rec = record.getRecord(); if (rec instanceof ODocument) { ODocument doc = (ODocument) rec; if (!doc.getIdentity().isPersistent() && doc.fields() == 1) { // EXTRACT THE FIELD CONTEXT Object fieldvalue = doc.field(doc.fieldNames()[0]); if (fieldvalue instanceof Collection<?>) { command.getContext().push( new OTraverseRecordSetProcess(command, ((Collection<OIdentifiable>) fieldvalue).iterator(), getPath())); } else if (fieldvalue instanceof ODocument) { command.getContext().push(new OTraverseRecordProcess(command, (ODocument) rec, getPath())); } } else { command.getContext().push(new OTraverseRecordProcess(command, (ODocument) rec, getPath())); } return null; } } return pop(); }
public <T> T getProperty(final String key) { if (key == null) return null; if (key.equals("_class")) return (T) getRecord().getSchemaClass().getName(); else if (key.equals("_version")) return (T) new Integer(getRecord().getVersion()); else if (key.equals("_rid")) return (T) rawElement.getIdentity().toString(); return getRecord().field(key); }
public static void realizeMandatory(ODocument doc) { OClass oClass = doc.getSchemaClass(); if(oClass!=null) { for(OProperty property : oClass.properties()) { if(property.isMandatory() && Strings.isEmpty(property.getDefaultValue()) && !doc.containsField(property.getName())) { doc.field(property.getName(), (Object) null); } } } }
@Override public ODocument storeDashboard() { ODocument doc = super.storeDashboard(); doc.field(OWidgetsModule.OPROPERTY_CLASS, getModelObject().getSchemaClass().getName()); doc.save(); return doc; } };
protected List<String> getTagEntityListDb(String host, String tagId) { List<String> entityList = null; OrientGraph graph = ServiceLocator.getInstance().getGraph(); try { OIndex<?> tagHostIdIdx = graph.getRawGraph().getMetadata().getIndexManager().getIndex("tagHostIdIdx"); OCompositeKey key = new OCompositeKey(host, tagId); OIdentifiable oid = (OIdentifiable) tagHostIdIdx.get(key); if (oid != null) { ODocument doc = (ODocument)oid.getRecord(); entityList = new ArrayList<String>(); ORidBag entities = doc.field("in_HasTag"); Iterator<OIdentifiable> iterator = entities.iterator(); while (iterator.hasNext()) { OIdentifiable identifiable = iterator.next(); entityList.add(identifiable.getIdentity().toString()); } } } catch (Exception e) { logger.error("Exception:", e); } finally { graph.shutdown(); } return entityList; }