Java Code Examples for com.tinkerpop.blueprints.Element

The following examples show how to use com.tinkerpop.blueprints.Element. 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: org.openntf.domino   Source File: DominoElement.java    License: Apache License 2.0 6 votes vote down vote up
public static Object getReflectiveProperty(final IDominoElement element, final String prop) {
	if (prop == null || prop.isEmpty())
		throw new IllegalArgumentException("Cannot set a null or empty property on a DominoElement");
	Object result = false;
	Class<? extends Element> elemClass = element.getClass();
	Method getter = BeanUtils.findGetter(elemClass, prop);
	if (getter != null) {
		try {
			result = getter.invoke(element, (Object[]) null);
		} catch (Exception e) {
			DominoUtils.handleException(e);
			System.out.println("Unable to invoke " + getter.getName() + " on a " + element.getClass() + " for property: " + prop);
		}
	} else {
		IDominoProperties domProp = IDominoProperties.Reflect.findMappedProperty(elemClass, prop);
		if (domProp != null) {
			result = element.getProperty(domProp);
		} else {
			result = element.getProperty(prop);
		}
	}
	return result;
}
 
Example 2
public <F> F frame(final Element element, final Class<F> kind) {
	//		Class<F> klazz = kind;
	//		DConfiguration config = (DConfiguration) this.getConfig();
	//		config.getTypeManager().initElement(klazz, this, element);
	//		for (FrameInitializer initializer : getConfig().getFrameInitializers()) {
	//			if (!(initializer instanceof JavaFrameInitializer)) {
	//				initializer.initElement(klazz, this, element);
	//			}
	//		}
	F result = null;
	if (element instanceof Edge) {
		result = frame((Edge) element, kind);
	} else if (element instanceof Vertex) {
		result = frame((Vertex) element, kind);
	} else {
		throw new IllegalStateException("Cannot frame an element of type " + element.getClass().getName());
	}
	//		for (FrameInitializer initializer : getConfig().getFrameInitializers()) {
	//			if (initializer instanceof JavaFrameInitializer) {
	//				((JavaFrameInitializer) initializer).initElement(klazz, this, result);
	//			}
	//		}
	return result;
}
 
Example 3
public <F> Iterable<F> getElements(final String classname) {
		org.openntf.domino.graph2.DElementStore store = null;
		DGraph base = (DGraph) this.getBaseGraph();
		Class<?> chkClass = getClassFromName(classname);
		if (chkClass != null) {
			store = base.findElementStore(chkClass);
			if (store != null) {
				String formulaFilter = org.openntf.domino.graph2.DGraph.Utils.getFramedElementFormula(chkClass);
				Iterable<Element> elements = (org.openntf.domino.graph2.impl.DElementIterable) store.getElements(formulaFilter);
				if (elements instanceof List) {
//					int size = ((List) elements).size();
					//					System.out.println("TEMP DEBUG Found a list of size " + size + " for kind " + classname);
				}
				return this.frameElements(elements, (Class<F>) chkClass);
			} else {
				//				System.out.println("TEMP DEBUG Unable to find an element store for type " + classname);
				return null;
			}
		} else {
			throw new IllegalArgumentException("Class " + classname + " not registered in graph");
		}
	}
 
Example 4
Source Project: org.openntf.domino   Source File: DConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
public Class<?> getType(final Class<?> typeHoldingTypeField, final String typeValue, final Element elem) {
	Class<?> result = null;
	DGraph graph = config_.getGraph();
	DElementStore store = graph.findElementStore(elem);
	TypeRegistry reg = storeTypeMap_.get(store);
	//			System.out.println("TEMP DEBUG Attempting to resolve type name " + typeValue + " with an element");
	if (reg == null) {
		result = getType(typeHoldingTypeField, typeValue);
	} else {
		result = reg.getType(typeHoldingTypeField, typeValue);
		//				System.out.println("TEMP DEBUG Used local element store for " + typeHoldingTypeField.getName() + " value " + typeValue
		//						+ " in registry " + System.identityHashCode(reg) + " resulting in type "
		//						+ (result == null ? "null" : result.getName()));
	}
	if (result == null) {
		result = findClassByName(typeValue);
	}
	//			System.out.println("TEMP DEBUG Returning type " + result.getName());
	return result;
}
 
Example 5
private Object processFormula(final Formula formula, final Element element) {
	Object result = null;
	if (element instanceof DElement) {
		Map<String, Object> rawDoc = ((DElement) element).getDelegate();
		if (rawDoc instanceof Document) {
			result = formula.getValue((Document) rawDoc);
			if (result instanceof Vector) {
				Vector<Object> v = (Vector) result;
				if (v.size() == 1) {
					result = v.get(0);
				}
			}
		}
	}
	return result;
}
 
Example 6
/**
 * For those graphs that do no support automatic reindexing of elements when a key is provided for indexing, this method can be used to simulate that behavior.
 * The elements in the graph are iterated and their properties (for the provided keys) are removed and then added.
 * Be sure that the key indices have been created prior to calling this method so that they can pick up the property mutations calls.
 * Finally, if the graph is a TransactionalGraph, then a 1000 mutation buffer is used for each commit.
 *
 * @param graph    the graph containing the provided elements
 * @param elements the elements to index into the key indices
 * @param keys     the keys of the key indices
 * @return the number of element properties that were indexed
 */
public static long reIndexElements(final Graph graph, final Iterable<? extends Element> elements, final Set<String> keys) {
    final boolean isTransactional = graph instanceof TransactionalGraph;
    long counter = 0;
    for (final Element element : elements) {
        for (final String key : keys) {
            final Object value = element.removeProperty(key);
            if (null != value) {
                counter++;
                element.setProperty(key, value);


                if (isTransactional && (counter % 1000 == 0)) {
                    ((TransactionalGraph) graph).commit();
                }
            }
        }
    }
    if (isTransactional) {
        ((TransactionalGraph) graph).commit();
    }
    return counter;
}
 
Example 7
Source Project: AccumuloGraph   Source File: MapReduceElement.java    License: Apache License 2.0 6 votes vote down vote up
public boolean equals(Object object) {
  if (object == this) {
    return true;
  } else if (object == null) {
    return false;
  } else if (!object.getClass().equals(getClass())) {
    return false;
  } else {
    Element element = (Element) object;
    if (id == null) {
      return element.getId() == null;
    } else {
      return id.equals(element.getId());
    }
  }
}
 
Example 8
Source Project: AccumuloGraph   Source File: BaseIndexValuesTableWrapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add the property to this index.
 * 
 * <p/>Note that this requires a round-trip to Accumulo to see
 * if the property exists if the provided key has an index.
 * So for best performance, create indices after bulk ingest.
 * <p/>If the force parameter is true, set the property regardless
 * of whether indexing is enabled for the given key. This is needed
 * for {@link IndexableGraph} operations.
 * @param element
 * @param key
 * @param value
 * @param force
 */
public void setPropertyForIndex(Element element, String key, Object value,
    boolean force) {
  AccumuloGraphUtils.validateProperty(key, value);
  if (force || globals.getConfig().getAutoIndex() ||
      globals.getIndexMetadataWrapper()
      .getIndexedKeys(elementType).contains(key)) {
    BatchWriter writer = getWriter();

    Object oldValue = element.getProperty(key);
    if (oldValue != null && !oldValue.equals(value)) {
      Mutators.apply(writer, new IndexValueMutator.Delete(element, key, oldValue));
    }

    Mutators.apply(writer, new IndexValueMutator.Add(element, key, value));
    globals.checkedFlush();
  }
}
 
Example 9
Source Project: antiquity   Source File: HasElementIds.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean matchesSafely(T t) {
    for (Element e : t) {
        if (id == ID.ID) {
            ids.add(e.getId());
        } else {
            if (!(e instanceof HistoricVersionedElement)) {
                throw new IllegalStateException("HARD_ID must be used with historic elements only");
            } else {
                HistoricVersionedElement he = (HistoricVersionedElement)e;
                ids.add(((HistoricVersionedElement) e).getHardId());
            }
        }
    }

    if (type == TYPE.CONTAINS) {
        return ids.containsAll(expected);
    } else if (type == TYPE.EXACTLY_MATCHES) {
        return (ids.containsAll(expected) && expected.containsAll(ids));
    }

    throw new IllegalStateException(("comparison type is unsupported."));
}
 
Example 10
Source Project: AccumuloGraph   Source File: IndexMetadataTableWrapper.java    License: Apache License 2.0 6 votes vote down vote up
public <T extends Element> Set<String> getIndexedKeys(Class<T> elementClass) {
  if (elementClass == null) {
    throw ExceptionFactory.classForElementCannotBeNull();
  }

  IndexedItemsListParser parser = new IndexedItemsListParser(elementClass);

  Scanner scan = null;
  try {
    scan = getScanner();
    scan.fetchColumnFamily(new Text(IndexMetadataEntryType.__INDEX_KEY__.name()));

    Set<String> keys = new HashSet<String>();
    for (IndexedItem item : parser.parse(scan)) {
      keys.add(item.getKey());
    }

    return keys;

  } finally {
    if (scan != null) {
      scan.close();
    }
  }
}
 
Example 11
Source Project: AccumuloGraph   Source File: ElementTableWrapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Read the given property from the backing table
 * for the given element id.
 * @param id
 * @param key
 * @return
 */
public <V> V readProperty(Element element, String key) {
  Scanner s = getScanner();

  s.setRange(new Range(element.getId().toString()));

  Text colf = StringFactory.LABEL.equals(key)
      ? new Text(Constants.LABEL) : new Text(key);
  s.fetchColumnFamily(colf);

  V value = null;

  Iterator<Entry<Key, Value>> iter = s.iterator();
  if (iter.hasNext()) {
    value = AccumuloByteSerializer.deserialize(iter.next().getValue().get());
  }
  s.close();

  return value;
}
 
Example 12
public <F> Iterable<F> getFilteredElements(final String classname, final List<CharSequence> keys,
		final List<CaseInsensitiveString> values) {
	//		System.out.println("Getting a filtered list of elements of type " + classname);
	org.openntf.domino.graph2.DElementStore store = null;
	DGraph base = (DGraph) this.getBaseGraph();
	Class<?> chkClass = getClassFromName(classname);
	if (chkClass != null) {
		store = base.findElementStore(chkClass);
		if (store != null) {
			List<String> keystrs = CaseInsensitiveString.toStrings(keys);
			List<Object> valobj = new ArrayList<Object>(values);
			String formulaFilter = org.openntf.domino.graph2.DGraph.Utils.getFramedElementFormula(keystrs, valobj, chkClass);
			long startTime = new Date().getTime();
			Iterable<Element> elements = (org.openntf.domino.graph2.impl.DElementIterable) store.getElements(formulaFilter);
			long endTime = new Date().getTime();
			System.out
					.println("TEMP DEBUG Retrieved elements for type " + classname + " in " + (endTime - startTime) + "ms. Framing...");
			return this.frameElements(elements, null);
		} else {
			return null;
		}
	} else {
		throw new IllegalArgumentException("Class " + classname + " not registered in graph");
	}
}
 
Example 13
Source Project: org.openntf.domino   Source File: IdGraph.java    License: Apache License 2.0 5 votes vote down vote up
public <T extends Element> Index<T> createIndex(final String indexName,
                                                final Class<T> indexClass,
                                                final Parameter... indexParameters) {
    verifyBaseGraphIsIndexableGraph();

    return isVertexClass(indexClass)
            ? (Index<T>) new IdVertexIndex((Index<Vertex>) ((IndexableGraph) baseGraph).createIndex(indexName, indexClass, indexParameters), this)
            : (Index<T>) new IdEdgeIndex((Index<Edge>) ((IndexableGraph) baseGraph).createIndex(indexName, indexClass, indexParameters), this);
}
 
Example 14
public <T extends Element> Index<T> getIndex(final String indexName, final Class<T> indexClass) {
    final Index<T> index = baseGraph.getIndex(indexName, indexClass);
    if (null == index)
        return null;
    else {
        return new PartitionIndex<T>(index, this);
    }
}
 
Example 15
Source Project: org.openntf.domino   Source File: DElementStore.java    License: Apache License 2.0 5 votes vote down vote up
protected LoadingCache<NoteCoordinate, Element> getElementCache() {
	if (elementCache_ == null) {
		elementCache_ = CacheBuilder.newBuilder().maximumSize(16384).expireAfterWrite(20, TimeUnit.HOURS)
				.build(new ElementStoreCacheLoader(this));
	}
	return elementCache_;
}
 
Example 16
@Override
public Object processElement(final InVertex annotation, final Method method, final Object[] arguments, final FramedGraph framedGraph, final Element element, final Direction direction) {
    if (element instanceof Edge) {
        return framedGraph.frame(((Edge)element).getVertex(Direction.IN), method.getReturnType());
    } else {
        throw new UnsupportedOperationException();
    }
}
 
Example 17
Source Project: org.openntf.domino   Source File: ElementHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A standard method for determining if two elements are equal.
 * This method should be used by any Element.equals() implementation to ensure consistent behavior.
 *
 * @param a The first element
 * @param b The second element (as an object)
 * @return Whether the two elements are equal
 */
public static boolean areEqual(final Element a, final Object b) {
    if (a == b)
        return true;
    if (null == b)
        return false;
    if (!a.getClass().equals(b.getClass()))
        return false;
    return a.getId().equals(((Element) b).getId());
}
 
Example 18
Source Project: org.openntf.domino   Source File: DConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
public Class<?> resolve(final Element e, final Class<?> defaultType) {
	//			System.out.println("Resolving element with default type " + defaultType.getName());
	Class<?> result = defaultType;
	Class<?> typeHoldingTypeField = typeRegistry_.getTypeHoldingTypeField(defaultType);
	if (typeHoldingTypeField != null) {
		String value = ((DElement) e).getProperty(typeHoldingTypeField.getAnnotation(TypeField.class).value(), String.class);
		//				System.out.println("TEMP DEBUG: Found type value: " + (value == null ? "null" : value));
		Class<?> type = null;
		try {
			type = value == null ? null : typeRegistry_.getType(typeHoldingTypeField, value, e);
		} catch (Throwable t) {
			if (e instanceof Edge) {
				type = typeRegistry_.config_.getDefaultEdgeFrameType();
			} else {
				type = typeRegistry_.config_.getDefaultVertexFrameType();
			}
		}
		if (type != null) {
			//					System.out.println("TEMP DEBUG: Returning type: " + type.getName());
			if (type.getSimpleName().equalsIgnoreCase(defaultType.getSimpleName())) {
				//						System.out.println("Simple name collision on vertex for name " + defaultType.getSimpleName()
				//								+ ". Using requested type: " + defaultType.getName());
				result = defaultType;
			} else {
				result = type;
			}
		}
	}
	//			System.out.println("TEMP DEBUG returning type " + result.getName());
	return result;
}
 
Example 19
Source Project: org.openntf.domino   Source File: ElementComparator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int compare(final Element arg0, final Element arg1) {
	int result = 0;
	if (dProps_ != null && dProps_.length > 0) {
		result = compareProps((IDominoElement) arg0, (IDominoElement) arg1);
	} else {
		result = compareStrs((IDominoElement) arg0, (IDominoElement) arg1);
	}
	return result;
}
 
Example 20
Source Project: org.openntf.domino   Source File: IncidenceHandler.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public Object processElement(final Incidence annotation, final Method method, final Object[] arguments, final FramedGraph framedGraph,
		final Element element, final Direction direction) {
	if (element instanceof Vertex) {
		return processVertexIncidence(annotation, method, arguments, framedGraph, (Vertex) element);
	} else {
		throw new UnsupportedOperationException();
	}
}
 
Example 21
Source Project: org.openntf.domino   Source File: TypeManager.java    License: Apache License 2.0 5 votes vote down vote up
private Class<?> resolve(Element e, Class<?> defaultType) {
	Class<?> typeHoldingTypeField = typeRegistry.getTypeHoldingTypeField(defaultType);
	if (typeHoldingTypeField != null) {
		String value = e.getProperty(typeHoldingTypeField.getAnnotation(TypeField.class).value());
		Class<?> type = value == null ? null : typeRegistry.getType(typeHoldingTypeField, value);
		if (type != null) {
			return type;
		}
	}
	return defaultType;
}
 
Example 22
Source Project: AccumuloGraph   Source File: GlobalInstances.java    License: Apache License 2.0 5 votes vote down vote up
public <T extends Element> ElementTableWrapper getElementWrapper(Class<T> clazz) {
  if (Vertex.class.equals(clazz)) {
    return getVertexWrapper();
  } else if (Edge.class.equals(clazz)) {
    return getEdgeWrapper();
  } else {
    throw new AccumuloGraphException("Unrecognized class: "+clazz);
  }
}
 
Example 23
Source Project: AccumuloGraph   Source File: GlobalInstances.java    License: Apache License 2.0 5 votes vote down vote up
public <T extends Element> BaseKeyIndexTableWrapper getKeyIndexTableWrapper(Class<T> clazz) {
  if (Vertex.class.equals(clazz)) {
    return getVertexKeyIndexWrapper();
  } else if (Edge.class.equals(clazz)) {
    return getEdgeKeyIndexWrapper();
  } else {
    throw new AccumuloGraphException("Unrecognized class: "+clazz);
  }    
}
 
Example 24
Source Project: org.openntf.domino   Source File: ElementHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether two elements have the same properties.
 * To be true, both must have the same property keys and respective values must be equals().
 *
 * @param a an element
 * @param b an element
 * @return whether the two elements have equal properties
 */
public static boolean haveEqualProperties(final Element a, final Element b) {
    final Set<String> aKeys = a.getPropertyKeys();
    final Set<String> bKeys = b.getPropertyKeys();

    if (aKeys.containsAll(bKeys) && bKeys.containsAll(aKeys)) {
        for (String key : aKeys) {
            if (!a.getProperty(key).equals(b.getProperty(key)))
                return false;
        }
        return true;
    } else {
        return false;
    }
}
 
Example 25
@Override
public Object processElement(final Adjacency annotation, final Method method, final Object[] arguments, final FramedGraph framedGraph,
        final Element element, final Direction direction) {
    if (element instanceof Vertex) {
        return processVertex(annotation, method, arguments, framedGraph, (Vertex) element);
    } else {
        throw new UnsupportedOperationException();
    }
}
 
Example 26
Source Project: AccumuloGraph   Source File: AccumuloGraph.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<Index<? extends Element>> getIndices() {
  if (globals.getConfig().getIndexableGraphDisabled()) {
    throw new UnsupportedOperationException("IndexableGraph is disabled via the configuration");
  }
  return globals.getIndexMetadataWrapper().getIndices();
}
 
Example 27
Source Project: AccumuloGraph   Source File: AccumuloGraph.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Clear out this graph. This drops and recreates the backing tables.
 */
public void clear() {
  shutdown();

  try {
    TableOperations tableOps = globals.getConfig()
        .getConnector().tableOperations();
    for (Index<? extends Element> index : getIndices()) {
      tableOps.delete(((AccumuloIndex<? extends Element>)
          index).getTableName());
    }

    for (String table : globals.getConfig().getTableNames()) {
      if (tableOps.exists(table)) {
        tableOps.delete(table);
        tableOps.create(table);

        SortedSet<Text> splits = globals.getConfig().getSplits();
        if (splits != null) {
          tableOps.addSplits(table, splits);
        }
      }
    }
  } catch (Exception e) {
    throw new AccumuloGraphException(e);
  }
}
 
Example 28
Source Project: org.openntf.domino   Source File: DominoGraph.java    License: Apache License 2.0 5 votes vote down vote up
public void startTransaction(final Element elem) {
	putCache(elem);
	if (getTxn() == null) {
		getRawDatabase().startTransaction();
		//			setTxn(getRawDatabase().startTransaction());
	}
}
 
Example 29
Source Project: antiquity   Source File: ElementUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a single element.
 * 
 * @param it iterable of elements.
 * @param <E> must be of {@link Element} type.
 * @return single element.
 * @throws IllegalStateException if multiple elements found.
 */
@SuppressWarnings("unchecked")
public static <E extends Element> E getSingleElement(Iterable<E> it) {
    Iterator<?> iter = it.iterator();
    E e = null;

    if (iter.hasNext()) {
        e = (E) iter.next();
    }


    if (iter.hasNext()) throw new IllegalStateException(String.format("Multiple elements found."));

    return e;
}
 
Example 30
Source Project: org.openntf.domino   Source File: IDominoProperties.java    License: Apache License 2.0 5 votes vote down vote up
public static IDominoProperties findMappedProperty(final Class<? extends Element> cls, final String prop) {
	IDominoProperties result = null;
	for (IDominoProperties curProp : getMappedProperties(cls)) {
		if (curProp.getName().equalsIgnoreCase(prop)) {
			result = curProp;
			break;
		}
	}
	return result;
}