Ejemplo n.º 1
0
        public override QueryResult GetResult(
            GQLPluginManager myPluginManager,
            IGraphDB myGraphDB,
            SecurityToken mySecurityToken,
            TransactionToken myTransactionToken)
        {
            var resultingVertices = new List<IVertexView>();
            ASonesException error = null;

            #region Specific index

            var request = new RequestDescribeIndex(_TypeName, _IndexName, _IndexEdition);

            var indices = myGraphDB.DescribeIndex<IEnumerable<IIndexDefinition>>(mySecurityToken, myTransactionToken, request, (stats, definitions) => definitions);

            if (indices == null)
            {
                error = new IndexTypeDoesNotExistException(_TypeName, _IndexName);
            }

            if (String.IsNullOrEmpty(_IndexEdition))
            {
                //_IndexEdition = DBConstants.DEFAULTINDEX;
            }

            resultingVertices = new List<IVertexView>() { GenerateOutput(indices, _IndexName) };

            #endregion

            if(error != null)
                return new QueryResult("", SonesGQLConstants.GQL, 0L, ResultType.Failed, resultingVertices, error);
            else
                return new QueryResult("", SonesGQLConstants.GQL, 0L, ResultType.Successful, resultingVertices);
        }
Ejemplo n.º 2
0
        public TagExample()
        {
            //Make a new GraphDB instance
            GraphDB = new SonesGraphDB();

            #region Configure PlugIns
            // Plugins are loaded by the GraphDS with their according PluginDefinition and only if they are listed
            // below - there is no auto-discovery for plugin types in GraphDS (!)

            #region Query Languages
            // the GQL Query Language Plugin needs the GraphDB instance as a parameter
            List<PluginDefinition> QueryLanguages = new List<PluginDefinition>();
            Dictionary<string, object> GQL_Parameters = new Dictionary<string, object>();
            GQL_Parameters.Add("GraphDB", GraphDB);

            QueryLanguages.Add(new PluginDefinition("sones.gql", GQL_Parameters));
            #endregion

            #endregion

            GraphDSPlugins PluginsAndParameters = new GraphDSPlugins(null, QueryLanguages);

            var credentials = new UserPasswordCredentials("User", "test");

            GraphDSServer = new GraphDS_Server(GraphDB, (ushort)9975, "User", "test", IPAddress.Any, PluginsAndParameters);
            GraphDSServer.LogOn(credentials);
            //GraphDSServer.StartRESTService("", Properties.Settings.Default.ListeningPort, IPAddress.Any);

            //get a Security- and TransactionToken
            SecToken = GraphDSServer.LogOn(credentials);
            TransToken = GraphDSServer.BeginTransaction(SecToken);
        }
Ejemplo n.º 3
0
        public override QueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
        {
            _query = myQuery;

            var vertexType = myGraphDB.GetVertexType<IVertexType>(
                mySecurityToken,
                myTransactionToken,
                new RequestGetVertexType(_typeName),
                (stats, vType) => vType);

            _WhereExpression.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, vertexType);

            var expressionGraph = _WhereExpression.Calculon(myPluginManager, myGraphDB, mySecurityToken,
                                                            myTransactionToken,
                                                            new CommonUsageGraph(myGraphDB, mySecurityToken,
                                                                                 myTransactionToken));

            var toBeDeletedVertices =
                expressionGraph.Select(
                    new LevelKey(vertexType.ID, myGraphDB, mySecurityToken, myTransactionToken),
                    null, true);

            //TODO: do sth that is better than that: ew RequestDelete(new RequestGetVertices(_typeName, toBeDeletedVertices.Select(_ => _.VertexID))).
            return myGraphDB.Delete<QueryResult>(
                mySecurityToken,
                myTransactionToken,
                new RequestDelete(new RequestGetVertices(_typeName, toBeDeletedVertices.Select(_ => _.VertexID))).AddAttributes(_toBeDeletedAttributes),
                CreateQueryResult);
        }
Ejemplo n.º 4
0
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken, params FuncParameter[] myParams)
        {
            if (!(myCallingObject is String))
            {
                throw new FunctionParameterTypeMismatchException(typeof(String), myCallingObject.GetType());
            }

            var pos = Convert.ToInt32(myParams[0].Value);

            StringBuilder resString = new StringBuilder();
            bool dontInsert = false;

            if (pos > (myCallingObject as String).Length)
            {
                dontInsert = true;
                resString.Append((myCallingObject as String).ToString());
            }
            else
            {
                resString.Append((myCallingObject as String).ToString().Substring(0, pos));
            }

            foreach (FuncParameter fp in myParams.Skip(1))
            {
                resString.Append(fp.Value as String);
            }

            if(!dontInsert)
                resString.Append((myCallingObject as String).ToString().Substring(pos));

            return new FuncParameter(resString.ToString());
        }
Ejemplo n.º 5
0
        public override QueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
        {
            Query = myQuery;

            var indexDef = new IndexPredefinition(_IndexName);
            indexDef.SetIndexType(_IndexType);
            indexDef.SetVertexType(_DBType);
            indexDef.SetEdition(_IndexEdition);

            //to be indices attributes
            foreach (var aIndexedProperty in _AttributeList)
            {
                indexDef.AddProperty(aIndexedProperty.IndexAttribute.ContentString);
            }

            //options for the index
            if (_options != null)
            {
                foreach (var aKV in _options)
                {
                    indexDef.AddOption(aKV.Key, aKV.Value);
                }
            }

            return myGraphDB.CreateIndex<QueryResult>(mySecurityToken, myTransactionToken, new RequestCreateIndex(indexDef), GenerateResult);
        }
Ejemplo n.º 6
0
        public override QueryResult Execute(IGraphDB myGraphDB, 
            IGraphQL myGraphQL,
            GQLPluginManager myPluginManager,
            String myQuery,
            SecurityToken mySecurityToken,
            Int64 myTransactionToken)
        {
            _queryString = myQuery;

            QueryResult result;

            try
            {
                result = myGraphDB.Insert<QueryResult>(
                        mySecurityToken,
                        myTransactionToken,
                        CreateRequest(myPluginManager,
                                        myGraphDB,
                                        mySecurityToken,
                                        myTransactionToken),
                        CreateQueryResult);
            }
            catch (ASonesException e)
            {
                result = new QueryResult(_queryString, SonesGQLConstants.GQL, 0, ResultType.Failed, null, e);
            }

            return result;
        }
Ejemplo n.º 7
0
        public override QueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
        {
            var sw = Stopwatch.StartNew();

            QueryResult result = null;

            if (_DumpFormat.ToString().ToUpper().Equals("GQL"))
            {
                var plugin = myPluginManager.GetAndInitializePlugin<IGraphDBExport>("GQLEXPORT");

                if (plugin != null)
                {
                    result = plugin.Export(_DumpDestination, _DumpableGrammar, myGraphDB, myGraphQL, mySecurityToken, myTransactionToken, _TypesToDump, _DumpType);
                }
            }

            sw.Stop();

            if (result != null)
            {
                return new QueryResult(myQuery, _DumpFormat.ToString(), (ulong)sw.ElapsedMilliseconds, result.TypeOfResult, result.Vertices, result.Error);
            }
            else
                return null;
        }
Ejemplo n.º 8
0
 public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken, params FuncParameter[] myParams)
 {
     if (myCallingObject is IHyperEdge)
     {
         return new FuncParameter((UInt64)((IHyperEdge)myCallingObject).GetAllEdges().Count());
     }
     else if (myCallingObject is ISingleEdge)
     {
         UInt64 count = 1;
         return new FuncParameter(count);
     }
     else if (myCallingObject is IncomingEdgeCollection)
     {
         return new FuncParameter((UInt64)(myCallingObject as IncomingEdgeCollection).LongCount());
     }
     else if (myCallingObject is IEnumerable<long>)
     {
         return new FuncParameter((UInt64)(myCallingObject as IEnumerable<long>).LongCount());
     }
     else if (myCallingObject is IEnumerable<IVertex>)
     {
         return new FuncParameter((UInt64)(myCallingObject as IEnumerable<IVertex>).LongCount());
     }
     else
     {
         throw new UnknownDBException("Unexpected input for COUNT aggregate.");
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Executes the function on myCallingObject
        /// </summary>
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken, params FuncParameter[] myParams)
        {
            var currentInnerEdgeType = ((IOutgoingEdgeDefinition)myAttributeDefinition).InnerEdgeType;

            if (myCallingObject is IHyperEdge && currentInnerEdgeType.HasProperty("Weight"))
            {
                var hyperEdge = myCallingObject as IHyperEdge;

                if (currentInnerEdgeType.HasProperty("Weight"))
                {
                    var weightProperty = currentInnerEdgeType.GetPropertyDefinition("Weight");

                    var maxWeight = hyperEdge.InvokeHyperEdgeFunc<Double>(singleEdges =>
                    {
                        return Convert.ToDouble(
                            weightProperty.GetValue(
                            singleEdges
                            .OrderByDescending(edge => weightProperty.GetValue(edge))
                            .First()));
                    });

                    return new FuncParameter(maxWeight);

                }
            }

            throw new InvalidTypeException(myCallingObject.GetType().ToString(), "Weighted IHyperEdge");
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Constructor
 /// </summary>
 public CommonUsageGraph(IGraphDB myIGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
     : this()
 {
     _iGraphDB = myIGraphDB;
     _securityToken = mySecurityToken;
     _transactionToken = myTransactionToken;
     _Levels = new Dictionary<int, IExpressionLevel>();
 }
Ejemplo n.º 11
0
        public LevelKey(IEnumerable<EdgeKey> myEdgeKey, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
        {
            Edges = new List<EdgeKey>();

            foreach (var aEdgeKey in myEdgeKey)
            {
                if (aEdgeKey.IsAttributeSet)
                {
                    var vertexType = myGraphDB.GetVertexType<IVertexType>
                        (mySecurityToken,
                        myTransactionToken,
                        new RequestGetVertexType(aEdgeKey.VertexTypeID),
                        (stats, type) => type);

                    var attribute = vertexType.GetAttributeDefinition(aEdgeKey.AttributeID);

                    if (attribute != null && attribute.Kind != AttributeType.Property)
                    {
                        //so there is an edge
                        Edges.Add(aEdgeKey);
                        Level++;

                        AddHashCodeFromSingleEdge(ref _hashcode, aEdgeKey);
                    }
                    else
                    {
                        if (Level == 0)
                        {
                            var newEdgeKey = new EdgeKey(aEdgeKey.VertexTypeID);
                            Edges.Add(newEdgeKey);

                            AddHashCodeFromSingleEdge(ref _hashcode, newEdgeKey);

                            break;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    if (Level == 0)
                    {
                        Edges.Add(aEdgeKey);

                        AddHashCodeFromSingleEdge(ref _hashcode, aEdgeKey);

                        break;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
Ejemplo n.º 12
0
        public override QueryResult GetResult(  GQLPluginManager myPluginManager,
            IGraphDB myGraphDB,
            SecurityToken mySecurityToken,
            Int64 myTransactionToken)
        {
            var resultingVertices = new List<IVertexView>();
            ASonesException error = null;

            if (!String.IsNullOrEmpty(_EdgeName))
            {

                #region Specific edge

                var request = new RequestGetEdgeType(_EdgeName);
                var edge = myGraphDB.GetEdgeType<IEdgeType>(mySecurityToken,
                                                            myTransactionToken,
                                                            request,
                                                            (stats, edgeType) => edgeType);

                if (edge != null)
                {
                    resultingVertices = new List<IVertexView>() { GenerateOutput(edge, _EdgeName) };
                }
                else
                {
                    error = new EdgeTypeDoesNotExistException(_EdgeName);
                }

                #endregion

            }
            else
            {

                #region All edges

                var resultingReadouts = new List<IVertexView>();

                var request = new RequestGetAllEdgeTypes();

                foreach (var edge in myGraphDB.GetAllEdgeTypes<IEnumerable<IEdgeType>>(mySecurityToken,
                                                                                        myTransactionToken,
                                                                                        request,
                                                                                        (stats, edgeTypes) => edgeTypes))
                {
                    resultingReadouts.Add(GenerateOutput(edge, edge.Name));
                }

                #endregion

            }

            if(error != null)
                return new QueryResult("", SonesGQLConstants.GQL, 0L, ResultType.Failed, resultingVertices, error);
            else
                return new QueryResult("", SonesGQLConstants.GQL, 0L, ResultType.Successful, resultingVertices);
        }
Ejemplo n.º 13
0
        public override QueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            _query = myQuery;

            return myGraphDB.AlterVertexType<QueryResult>(
                mySecurityToken,
                myTransactionToken,
                CreateNewRequest(myGraphDB, myPluginManager, mySecurityToken, myTransactionToken),
                CreateOutput);
        }
Ejemplo n.º 14
0
        public override IEnumerable<IVertexView> GetResult(
                                                GQLPluginManager myPluginManager,
                                                IGraphDB myGraphDB,
                                                SecurityToken mySecurityToken,
                                                Int64 myTransactionToken)
        {
            var resultingVertices = new List<IVertexView>();

            if (!String.IsNullOrEmpty(_EdgeName))
            {

                #region Specific edge

                var request = new RequestGetEdgeType(_EdgeName);
                var edge = myGraphDB.GetEdgeType<IEdgeType>(mySecurityToken, 
                                                            myTransactionToken, 
                                                            request, 
                                                            (stats, edgeType) => edgeType);

                if (edge != null)
                {
                    resultingVertices = new List<IVertexView>() { GenerateOutput(edge, _EdgeName) };
                }
                else
                {
                    throw new EdgeTypeDoesNotExistException(_EdgeName);
                }

                #endregion

            }
            else
            {

                #region All edges

                var resultingReadouts = new List<IVertexView>();

                var request = new RequestGetAllEdgeTypes();

                foreach (var edge in myGraphDB.GetAllEdgeTypes<IEnumerable<IEdgeType>>(mySecurityToken,     
                                                                                        myTransactionToken, 
                                                                                        request, 
                                                                                        (stats, edgeTypes) => edgeTypes))
                {
                    resultingReadouts.Add(GenerateOutput(edge, edge.Name));
                }


                #endregion

            }

            return resultingVertices;
        }
Ejemplo n.º 15
0
        public List<TypeWithProperty> StringParser(String current_string, IGraphDB myDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            current_string = current_string.Replace(" ","");

            List<TypeWithProperty> list = new List<TypeWithProperty>();
            bool endFlag = false;
            int EndPos = 0;

                do
                {

                    EndPos = current_string.IndexOf(',');
                    if (EndPos == -1)
                    {
                        EndPos = current_string.Length;
                        endFlag = true;
                    }

                    var typeVertexString = current_string.Substring(0, current_string.IndexOf('.'));


                    IVertexType typeVertex = null;

                    try
                    {

                        typeVertex = myDB.GetVertexType<IVertexType>(
                                                         mySecurityToken,
                                                         myTransactionToken,
                                                         new sones.GraphDB.Request.RequestGetVertexType(typeVertexString),
                                                         (statistics, type) => type);
                    }
                    catch
                    {
                        throw new InvalidFunctionParameterException("edgeType", "Object reference not set to an instance of an object.", "null");
                    }
                    var propertyIDString = current_string.Substring(current_string.IndexOf('.') + 1, EndPos - current_string.IndexOf('.') - 1);
                    var property = typeVertex.GetPropertyDefinition(propertyIDString);
                     if (property==null)
                         throw new InvalidFunctionParameterException("Property", "Property: " + propertyIDString + " not exist in VertexType:" + typeVertexString, "null");
                    TypeWithProperty value = new TypeWithProperty();
                    value.propertyDifinition = property;
                    value.type = typeVertex;

                    if (!list.Contains(value))
                        list.Add(value);

                    if (!endFlag)
                        current_string = current_string.Substring(EndPos + 1);

                }
                while (endFlag != true);
 
            return list;
        }
Ejemplo n.º 16
0
 public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken, params FuncParameter[] myParams)
 {
     if (myCallingObject != null)
     {
         return new FuncParameter(true);
     }
     else
     {
         return new FuncParameter(false);
     }
 }
Ejemplo n.º 17
0
        public QueryResult Import(String myLocation, IGraphDB myGraphDB, IGraphQL myGraphQL, SecurityToken mySecurityToken, TransactionToken myTransactionToken, UInt32 myParallelTasks = 1U, IEnumerable<string> myComments = null, UInt64? myOffset = null, UInt64? myLimit = null, VerbosityTypes myVerbosityType = VerbosityTypes.Silent)
        {
            ASonesException error;
            Stream stream = null;
            QueryResult result;

            #region Read querie lines from location

            try
            {
                #region file
                if (myLocation.ToLower().StartsWith(@"file:\\"))
                {
                    //lines = ReadFile(location.Substring(@"file:\\".Length));
                    stream = GetStreamFromFile(myLocation.Substring(@"file:\\".Length));
                }
                #endregion
                #region http
                else if (myLocation.ToLower().StartsWith("http://"))
                {
                    stream = GetStreamFromHttp(myLocation);
                }
                #endregion
                else
                {
                    error = new InvalidImportLocationException(myLocation, @"file:\\", "http://");
                    result = new QueryResult("", ImportFormat, 0L, ResultType.Failed, null, error);
                    return result;
                }

                #region Start import using the AGraphDBImport implementation and return the result

                return Import(stream, myGraphDB, myGraphQL, mySecurityToken, myTransactionToken, myParallelTasks, myComments, myOffset, myLimit, myVerbosityType);

                #endregion
            }
            catch (Exception ex)
            {
                #region throw new exception
                error = new ImportFailedException(ex);
                result = new QueryResult("", ImportFormat, 0L, ResultType.Failed, null, error);
                return result;
                #endregion
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            #endregion
        }
Ejemplo n.º 18
0
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, params FuncParameter[] myParams)
        {
            if (!(myCallingObject is String))
            {
                throw new FunctionParameterTypeMismatchException(typeof(String), myCallingObject.GetType());
            }

            var substring = myCallingObject.ToString().Substring(Convert.ToInt32(myParams[0].Value), Convert.ToInt32(myParams[1].Value));

            return new FuncParameter(substring);
        }
Ejemplo n.º 19
0
 public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, params FuncParameter[] myParams)
 {
     if (myCallingObject is String)
     {
         return new FuncParameter(((String)myCallingObject).ToLower());
     }
     else
     {
         throw new FunctionParameterTypeMismatchException(typeof(String), myCallingObject.GetType());
     }
 }
Ejemplo n.º 20
0
        public override QueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            var sw = Stopwatch.StartNew();

            QueryResult result = null;
            _query = myQuery;
            String myAction = "";
            IEnumerable<IVertex> myToBeUpdatedVertices = null;

            //prepare
            var vertexType = myGraphDB.GetVertexType<IVertexType>(
                mySecurityToken,
                myTransactionToken,
                new RequestGetVertexType(_Type),
                (stats, vtype) => vtype);

            if (_WhereExpression != null)
            {
                //validate
                _WhereExpression.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, vertexType);

                //calculate
                var expressionGraph = _WhereExpression.Calculon(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, new CommonUsageGraph(myGraphDB, mySecurityToken, myTransactionToken), false);

                //extract
                myToBeUpdatedVertices = expressionGraph.Select(new LevelKey(vertexType.ID, myGraphDB, mySecurityToken, myTransactionToken), null, true).ToList();
            }

            if (myToBeUpdatedVertices != null && myToBeUpdatedVertices.Count() > 0)
            {

                //update
                result = ProcessUpdate(myToBeUpdatedVertices, myGraphDB, myPluginManager, mySecurityToken, myTransactionToken);
                myAction = "Updated";

            }
            else
            {

                //insert
                result = ProcessInsert(myGraphDB, myPluginManager, mySecurityToken, myTransactionToken);
                myAction = "Inserted";

            }

            if (result.Error != null)
                throw result.Error;

            sw.Stop();

            return GenerateResult(sw.Elapsed.TotalMilliseconds, result, myAction);
        }
Ejemplo n.º 21
0
        public override IQueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            try
            {
                var stat = myGraphDB.Truncate(mySecurityToken, myTransactionToken, new RequestTruncate(_TypeName), (stats) => stats);

                return QueryResult.Success(myQuery, SonesGQLConstants.GQL, null, Convert.ToUInt64(stat.ExecutionTime.Milliseconds));
            }
            catch(ASonesException e)
            {
                return QueryResult.Failure(myQuery, SonesGQLConstants.GQL, e);
            }
        }
Ejemplo n.º 22
0
        public override IQueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            try
            {
                var request = new RequestRebuildIndices(_Types);

                return myGraphDB.RebuildIndices<IQueryResult>(mySecurityToken, myTransactionToken, request, _=> GenerateOutput(myQuery, _));
            }
            catch (ASonesException ex)
            {
                return QueryResult.Failure(myQuery, SonesGQLConstants.GQL, ex);
            }
        }
Ejemplo n.º 23
0
        public override IQueryResult Execute(IGraphDB myGraphDB,
                                            IGraphQL myGraphQL,
                                            GQLPluginManager myPluginManager,
                                            String myQuery,
                                            SecurityToken mySecurityToken,
                                            Int64 myTransactionToken)
        {
            _query = myQuery;

            return myGraphDB.DropEdgeType(mySecurityToken,
                                            myTransactionToken,
                                            new RequestDropEdgeType(_TypeName),
                                            GenerateOutput);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// <seealso cref=" ADescribeDefinition"/>
        /// </summary>
        public override QueryResult GetResult(GQLPluginManager myPluginManager,
            IGraphDB myGraphDB,
            SecurityToken mySecurityToken,
            TransactionToken myTransactionToken)
        {
            var resultingVertices = new List<IVertexView>();
            ASonesException error = null;

            if (!String.IsNullOrEmpty(_TypeName))
            {

                #region Specific type

                var request = new RequestGetVertexType(_TypeName);
                var type = myGraphDB.GetVertexType<IVertexType>(mySecurityToken, myTransactionToken, request, (stats, vertexType) => vertexType);

                if (type != null)
                {
                    resultingVertices = new List<IVertexView>() { (GenerateOutput(type, 1)) };
                }
                else
                {
                    error = new VertexTypeDoesNotExistException(_TypeName, "");
                }

                #endregion

            }
            else
            {

                #region All types

                foreach (var type in myGraphDB.GetAllVertexTypes<IEnumerable<IVertexType>>(mySecurityToken,
                                                                                            myTransactionToken,
                                                                                            new RequestGetAllVertexTypes(),
                                                                                            (stats, vertexTypes) => vertexTypes))
                {
                    resultingVertices.Add(GenerateOutput(type));
                }

                #endregion
            }

            if (error != null)
                return new QueryResult("", SonesGQLConstants.GQL, 0L, ResultType.Failed, resultingVertices, error);
            else
                return new QueryResult("", SonesGQLConstants.GQL, 0L, ResultType.Successful, resultingVertices);
        }
Ejemplo n.º 25
0
 public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken, params FuncParameter[] myParams)
 {
     if (myCallingObject is UInt64)
     {
         var dtValue = Convert.ToDateTime((UInt64)myCallingObject);
         return new FuncParameter((Int64)UNIXTimeConversionExtension.ToUnixTimeStamp(dtValue));
     }
     else if (myCallingObject is DateTime)
     {
         return new FuncParameter(UNIXTimeConversionExtension.ToUnixTimeStamp((DateTime)myCallingObject));
     }
     else
     {
         throw new InvalidTypeException(myCallingObject.GetType().ToString(), "DateTime");
     }
 }
Ejemplo n.º 26
0
        public BinaryExpressionDefinition GetBinaryExpression(GQLPluginManager myPluginManager, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
        {
            AExpressionDefinition right;
            var op = GetOperatorBySymbol(_OperatorSymbol);
            if (op == null)
            {
                throw new OperatorDoesNotExistException(_OperatorSymbol);
            }

            right = new ValueDefinition(1);

            var binExpr = new BinaryExpressionDefinition("*", _Expression, right);
            binExpr.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);

            return binExpr;
        }
Ejemplo n.º 27
0
        public override QueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
        {
            QueryResult result = new QueryResult(myQuery, SonesGQLConstants.GQL, 0L, ResultType.Failed);

            try
            {
                var stat = myGraphDB.Truncate(mySecurityToken, myTransactionToken, new RequestTruncate(_TypeName), (stats) => stats);

                result = new QueryResult(myQuery, SonesGQLConstants.GQL, Convert.ToUInt64(stat.ExecutionTime.Milliseconds), ResultType.Successful);
            }
            catch(ASonesException e)
            {
                result = new QueryResult(myQuery, SonesGQLConstants.GQL, 0, ResultType.Failed, null, e);
            }

            return result;
        }
Ejemplo n.º 28
0
        /// <summary>
        /// <seealso cref=" ADescribeDefinition"/>
        /// </summary>
        public override IEnumerable<IVertexView> GetResult(GQLPluginManager myPluginManager,
                                                IGraphDB myGraphDB,
                                                SecurityToken mySecurityToken,
                                                Int64 myTransactionToken)
        {
            var resultingVertices = new List<IVertexView>();

            if (!String.IsNullOrEmpty(_TypeName))
            {

                #region Specific type

                var request = new RequestGetVertexType(_TypeName);
                var type = myGraphDB.GetVertexType<IVertexType>(mySecurityToken, myTransactionToken, request, (stats, vertexType) => vertexType);

                if (type != null)
                {
                    resultingVertices = new List<IVertexView>() { (GenerateOutput(type, 1)) };
                }
                else
                {
                    throw new VertexTypeDoesNotExistException(_TypeName, "");
                }

                #endregion

            }
            else
            {

                #region All types

                foreach (var type in myGraphDB.GetAllVertexTypes<IEnumerable<IVertexType>>(mySecurityToken,
                                                                                            myTransactionToken,
                                                                                            new RequestGetAllVertexTypes(),
                                                                                            (stats, vertexTypes) => vertexTypes))
                {
                    resultingVertices.Add(GenerateOutput(type));
                }

                #endregion
            }

            return resultingVertices;
        }
Ejemplo n.º 29
0
        public override QueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
        {
            QueryResult qresult = null;
            Query = myQuery;

            try
            {
                var request = new RequestRebuildIndices(_Types);

                qresult = myGraphDB.RebuildIndices<QueryResult>(mySecurityToken, myTransactionToken, request, GenerateOutput);
            }
            catch (ASonesException e)
            {
                qresult.Error = e;
            }

            return qresult;
        }
Ejemplo n.º 30
0
        public override QueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, TransactionToken myTransactionToken)
        {
            QueryResult qresult = null;
            ASonesException error = null;

            try
            {
                var stat = myGraphDB.DropIndex(mySecurityToken, myTransactionToken, new RequestDropIndex(_TypeName, _IndexName, _IndexEdition), (stats) => stats);

                qresult = new QueryResult(myQuery, "sones.gql", Convert.ToUInt64(stat.ExecutionTime.Milliseconds), ResultType.Successful);
            }
            catch (ASonesException e)
            {
                error = e;
            }

            return new QueryResult(myQuery, "sones.gql", qresult.Duration, qresult.TypeOfResult, qresult.Vertices, error);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Finds matching result corresponding to a binary expression.
        /// </summary>
        /// <param name="myLeftValueObject">The left value of a binary expression.</param>
        /// <param name="myRightValueObject">The right value of a binary expression.</param>
        /// <param name="myPluginManager"></param>
        /// <param name="myGraphDB"></param>
        /// <param name="mySecurityToken"></param>
        /// <param name="myTransactionToken"></param>
        /// <param name="typeOfBinExpr">Type of the binary expression.</param>
        /// <param name="resultGr"></param>
        /// <param name="mytypesOfOpertators"></param>
        /// <param name="myOperator">The binary operator.</param>
        /// <param name="myExpressionIndex">The name of the index which should be used for the expression.</param>
        /// <param name="aggregateAllowed"></param>
        /// <returns>An expression graph.</returns>
        public static IExpressionGraph TypeOperation(AExpressionDefinition myLeftValueObject,
                                                     AExpressionDefinition myRightValueObject,
                                                     GQLPluginManager myPluginManager,
                                                     IGraphDB myGraphDB,
                                                     SecurityToken mySecurityToken,
                                                     Int64 myTransactionToken,
                                                     TypesOfBinaryExpression typeOfBinExpr,
                                                     IExpressionGraph resultGr,
                                                     TypesOfOperators mytypesOfOpertators,
                                                     BinaryOperator myOperator,
                                                     String myExpressionIndex,
                                                     Boolean aggregateAllowed = true)
        {
            #region Data

            //DataContainer for all data that is used by a binary expression/comparer
            DataContainer data;

            #endregion

            #region extract data

            //data extraction with an eye on the type of the binary expression

            switch (typeOfBinExpr)
            {
            case TypesOfBinaryExpression.Atom:

                //sth like 3 = 4
                #region Get Atom data

                //no further data has to be generated

                //data = new DataContainer(null, new Tuple<Object, Object>(myLeftValueObject, myRightValueObject), null);
                data = new DataContainer();

                #endregion

                break;

            case TypesOfBinaryExpression.LeftComplex:

                //sth like U.Age = 21
                #region Get LeftComplex data

                data = ExtractData(myLeftValueObject,
                                   myRightValueObject,
                                   ref typeOfBinExpr,
                                   myPluginManager,
                                   myGraphDB,
                                   mySecurityToken,
                                   myTransactionToken,
                                   aggregateAllowed);

                #endregion

                break;

            case TypesOfBinaryExpression.RightComplex:

                //sth like 21 = U.Age
                #region Get RightComplex data

                data = ExtractData(myRightValueObject,
                                   myLeftValueObject,
                                   ref typeOfBinExpr,
                                   myPluginManager,
                                   myGraphDB,
                                   mySecurityToken,
                                   myTransactionToken,
                                   aggregateAllowed);

                #endregion

                break;

            case TypesOfBinaryExpression.Complex:

                //sth like U.Age = F.Alter
                #region Get Complex data

                var leftData = ExtractData(myLeftValueObject,
                                           myRightValueObject,
                                           ref typeOfBinExpr,
                                           myPluginManager,
                                           myGraphDB,
                                           mySecurityToken,
                                           myTransactionToken,
                                           aggregateAllowed);

                var rightData = ExtractData(myRightValueObject,
                                            myLeftValueObject,
                                            ref typeOfBinExpr,
                                            myPluginManager,
                                            myGraphDB,
                                            mySecurityToken,
                                            myTransactionToken,
                                            aggregateAllowed);

                if (typeOfBinExpr == TypesOfBinaryExpression.Unknown)
                {
                    typeOfBinExpr = SetTypeOfBinaryExpression(leftData, rightData);

                    switch (typeOfBinExpr)
                    {
                    case TypesOfBinaryExpression.Atom:

                        data = new DataContainer(new Tuple <IDChainDefinition,
                                                            IDChainDefinition>(null, null),
                                                 new Tuple <AExpressionDefinition, AExpressionDefinition>(leftData.Operands.Item1, leftData.Operands.Item1),
                                                 new Tuple <AExpressionDefinition, AExpressionDefinition>(null, null));

                        break;

                    case TypesOfBinaryExpression.LeftComplex:

                        data = new DataContainer(new Tuple <IDChainDefinition, IDChainDefinition>(leftData.IDChainDefinitions.Item1, null),
                                                 new Tuple <AExpressionDefinition, AExpressionDefinition>(rightData.Operands.Item1, null),
                                                 new Tuple <AExpressionDefinition, AExpressionDefinition>(null, null));

                        break;

                    case TypesOfBinaryExpression.RightComplex:

                        data = new DataContainer(new Tuple <IDChainDefinition, IDChainDefinition>(rightData.IDChainDefinitions.Item1, null),
                                                 new Tuple <AExpressionDefinition, AExpressionDefinition>(leftData.Operands.Item1, null),
                                                 new Tuple <AExpressionDefinition, AExpressionDefinition>(null, null));

                        break;

                    case TypesOfBinaryExpression.Complex:
                    case TypesOfBinaryExpression.Unknown:
                    default:

                        throw new NotImplementedQLException("");
                    }
                }
                else
                {
                    data = JoinData(leftData, rightData);
                }

                #endregion

                break;

            default:

                throw new ArgumentException();
            }

            #endregion

            #region match data

            switch (typeOfBinExpr)
            {
            case TypesOfBinaryExpression.Atom:

                #region Atom

                //do nothing 3 = 3 (or 2 != 3) doesnt bother U

                #endregion

                break;

            case TypesOfBinaryExpression.LeftComplex:

                #region LeftComplex

                MatchData(data,
                          resultGr,
                          myGraphDB,
                          mySecurityToken,
                          myTransactionToken,
                          mytypesOfOpertators,
                          myOperator,
                          myExpressionIndex);

                #endregion

                break;

            case TypesOfBinaryExpression.RightComplex:

                #region RightComplex

                MatchData(data,
                          resultGr,
                          myGraphDB,
                          mySecurityToken,
                          myTransactionToken,
                          mytypesOfOpertators,
                          myOperator,
                          myExpressionIndex);

                #endregion

                break;

            case TypesOfBinaryExpression.Complex:

                #region Complex

                throw new NotImplementedQLException("");

                #endregion
            }

            #endregion

            return(resultGr);
        }
Ejemplo n.º 32
0
 public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, params FuncParameter[] myParams)
 {
     if (myCallingObject is UInt64)
     {
         var dtValue = Convert.ToDateTime((UInt64)myCallingObject);
         return(new FuncParameter((Int64)UNIXTimeConversionExtension.ToUnixTimeStamp(dtValue)));
     }
     else if (myCallingObject is Int64)
     {
         var dtValue = Convert.ToDateTime((Int64)myCallingObject);
         return(new FuncParameter((Int64)UNIXTimeConversionExtension.ToUnixTimeStamp(dtValue)));
     }
     else if (myCallingObject is DateTime)
     {
         return(new FuncParameter(UNIXTimeConversionExtension.ToUnixTimeStamp((DateTime)myCallingObject)));
     }
     else
     {
         throw new InvalidTypeException(myCallingObject.GetType().ToString(), "DateTime");
     }
 }
Ejemplo n.º 33
0
        private static LevelKey CreateLevelKey(IDChainDefinition myIDChainDefinition, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            if (myIDChainDefinition.Level == 0)
            {
                return(new LevelKey(new List <EdgeKey>()
                {
                    new EdgeKey(myIDChainDefinition.Edges[0].VertexTypeID)
                }, myGraphDB, mySecurityToken, myTransactionToken));
            }
            else
            {
                if (myIDChainDefinition.Last() is ChainPartFuncDefinition)
                {
                    // the funtion in the last idnode part processes the last attribute

                    if (myIDChainDefinition.Level == 1)
                    {
                        return(new LevelKey(new List <EdgeKey>()
                        {
                            new EdgeKey(myIDChainDefinition.Edges[0].VertexTypeID)
                        }, myGraphDB, mySecurityToken, myTransactionToken));
                    }
                    else
                    {
                        return(new LevelKey(myIDChainDefinition.Edges.Take(myIDChainDefinition.Level - 1), myGraphDB, mySecurityToken, myTransactionToken));
                    }
                }
                else
                {
                    return(new LevelKey(myIDChainDefinition.Edges.Take(myIDChainDefinition.Level), myGraphDB, mySecurityToken, myTransactionToken));
                }
            }
        }
Ejemplo n.º 34
0
 //Ctor
 public SocialUserManager()
 {
     _graphDB = new Neo4jDB();
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Validates the id chain if it is not already validated and returns all errors and warnings.
        /// </summary>
        public void Validate(GQLPluginManager myPluginManager, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, Dictionary <String, IVertexType> myListOfReferences, Boolean allowUndefinedAttributes = false)
        {
            IsValidated = true;

            int    _HashCode       = 0;
            Object funcWorkingBase = null;
            var    curPart         = RootPart;

            if (curPart == null)
            {
                if (myListOfReferences.Count != 1)
                {
                    throw new DuplicateReferenceOccurrenceException("");
                }

                _Reference = new Tuple <string, IVertexType>(myListOfReferences.First().Key, myListOfReferences.First().Value);
                _LastType  = _Reference.Item2;
                _Edges     = new List <EdgeKey>();
                _Edges.Add(new EdgeKey(_LastType.ID));
                SelectType = TypesOfSelect.Asterisk;
                LevelKey   = new LevelKey(_Edges, myGraphDB, mySecurityToken, myTransactionToken);
            }

            while (curPart != null)
            {
                #region Go through each part and try to fill lastType, lastAttribute etc...

                if (curPart is ChainPartFuncDefinition)
                {
                    #region ChainPartFuncDefinition

                    var funcPart = (curPart as ChainPartFuncDefinition);
                    funcPart.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);

                    if (!funcPart.Function.ValidateWorkingBase(funcWorkingBase, myGraphDB, mySecurityToken, myTransactionToken))
                    {
                        throw new InvalidFunctionBaseException(_LastAttribute.Name, funcPart.FuncName);
                    }

                    var returnType = funcPart.Function.GetReturnType();
                    if (returnType != null)
                    {
                        if (returnType is IAttributeDefinition)
                        {
                            //_LastAttribute = (returnType as DBTypeAttribute).GetValue();
                            //_LastType = GetDBTypeByAttribute(myDBContext, _LastAttribute);
                        }
                        else if (returnType is Object)
                        {
                            //_LastAttribute = null;
                            //_LastType = (returnType as DBType).GetValue();
                        }
                        else if (returnType is Type)
                        {
                            //_LastAttribute = null;
                            //_LastType = myDBContext.DBTypeManager.GetTypeByName((returnType as ADBBaseObject).ObjectName);
                        }
                        else
                        {
                            throw new InvalidFunctionReturnTypeException(funcPart.FuncName, returnType.GetType(), typeof(IAttributeDefinition), typeof(IVertexType), typeof(Object));
                        }
                        funcWorkingBase = returnType;
                    }

                    #endregion
                }
                else if (curPart is ChainPartTypeOrAttributeDefinition)
                {
                    var typeOrAttr = curPart as ChainPartTypeOrAttributeDefinition;

                    #region Check whether it is a reference

                    if (_LastAttribute != null)
                    {
                        #region Any attribute on an undefined attributes or not user defined (reference) type is not allowed

                        if (_LastAttribute is UnstructuredProperty || _LastAttribute.Kind == AttributeType.Property)
                        {
                            throw new VertexAttributeIsNotDefinedException(typeOrAttr.TypeOrAttributeName);
                        }

                        #endregion

                        #region The previous attribute seems to be an reference attribute

                        _LastType = GetTargetVertexTypeByAttribute(_LastAttribute);

                        typeOrAttr.DBType        = _LastType;
                        typeOrAttr.TypeAttribute = typeOrAttr.DBType.GetAttributeDefinition(typeOrAttr.TypeOrAttributeName);
                        _LastAttribute           = typeOrAttr.TypeAttribute;

                        if (_LastAttribute == null)
                        {
                            #region Undefined attribute

                            if (allowUndefinedAttributes)
                            {
                                UndefinedAttribute       = typeOrAttr.TypeOrAttributeName;
                                _LastAttribute           = new UnstructuredProperty(UndefinedAttribute);
                                typeOrAttr.TypeAttribute = _LastAttribute;
                                AddNewEdgeKey(_LastType, _LastAttribute.ID);
                            }
                            else
                            {
                                throw new VertexAttributeIsNotDefinedException(typeOrAttr.TypeOrAttributeName);
                            }

                            #endregion
                        }
                        else
                        {
                            AddNewEdgeKey(_LastType, _LastAttribute.ID);
                        }

                        #endregion
                    }
                    else if (_LastType == null)
                    {
                        #region We did not resolve any type - so we should have a reference (U.Friends) or an undefined attribute

                        if (myListOfReferences.ContainsKey(typeOrAttr.TypeOrAttributeName))
                        {
                            #region The current TypeOrAttributeName is either an reference U

                            typeOrAttr.DBType = myListOfReferences[typeOrAttr.TypeOrAttributeName];

                            //Case 1: sth like "U" (where U stands for User)
                            #region Case 1

                            _LastType  = typeOrAttr.DBType;
                            _Reference = new Tuple <string, IVertexType>(typeOrAttr.TypeOrAttributeName, typeOrAttr.DBType);

                            if (curPart.Next == null) // we just have an type definition
                            {
                                SelectType = TypesOfSelect.Asterisk;
                                _Edges.Add(new EdgeKey(_LastType.ID));
                            }

                            #endregion

                            //Case 2: an attribute like "Car" (of "User") is used and in parallel a similar written Type exists. In this case
                            // it is necessary to throw an error.
                            #region Case 2

                            var typesWithAttibute = (from aContextType in myListOfReferences
                                                     where (aContextType.Key != typeOrAttr.TypeOrAttributeName) && aContextType.Value.GetAttributeDefinition(typeOrAttr.TypeOrAttributeName) != null
                                                     select aContextType.Key).FirstOrDefault();

                            if (typesWithAttibute != null)
                            {
                                throw new DuplicateReferenceOccurrenceException(typeOrAttr.TypeOrAttributeName);
                            }

                            #endregion

                            #region Skip this part - this is a reference

                            RootPart = curPart.Next;

                            #endregion

                            #endregion
                        }
                        else
                        {
                            //Case 3:
                            //  (3.1)In this case it must be an attribute. If it is used in an ambigous way, an exception would be thrown.
                            //  (3.2)In this case it can be an undefined attribute or if it was used like an edge it is treated like does not exist (U.NotExists.Name)

                            #region case 3

                            #region sth like Name --> we have to find out the corresponding type

                            Boolean foundSth  = false;
                            String  reference = null;
                            foreach (var contextElement in myListOfReferences)
                            {
                                var tempAttr = contextElement.Value.GetAttributeDefinition(typeOrAttr.TypeOrAttributeName);


                                //tempTypeAttribute = (from aAttribute in tempType.AttributeLookupTable where aAttribute.Value.Name == tempTypeOrAttributeName select aAttribute.Value).FirstOrDefault();

                                if (tempAttr != null)
                                {
                                    typeOrAttr.DBType = contextElement.Value;
                                    reference         = contextElement.Key;

                                    if (foundSth == true)
                                    {
                                        throw new AmbiguousVertexAttributeException("The attribute or type \"" + typeOrAttr.TypeOrAttributeName + "\" has been used ambigous.");
                                    }
                                    else
                                    {
                                        typeOrAttr.TypeAttribute = tempAttr;
                                        foundSth = true;
                                    }
                                }
                            }

                            #endregion

                            if (foundSth)
                            {
                                #region 3.1

                                //_Edges.Add(new EdgeKey(typeOrAttr.DBType.VertexID, typeOrAttr.TypeAttribute.VertexID));
                                _LastAttribute = typeOrAttr.TypeAttribute;
                                _LastType      = typeOrAttr.DBType;
                                _Reference     = new Tuple <string, IVertexType>(reference, typeOrAttr.DBType); //T1 -->key in context dictionary

                                _Edges.ForEach(item => _HashCode = _HashCode ^ item.GetHashCode());
                                AddNewEdgeKey(_LastType, _LastAttribute.ID);

                                #endregion
                            }
                            else
                            {
                                #region 3.2 - Undefined attribute or attribute does not exist

                                if (curPart.Next != null || !allowUndefinedAttributes)
                                {
                                    #region Calling an attribute on an undefined attribute is not allowed

                                    throw new VertexAttributeIsNotDefinedException(typeOrAttr.TypeOrAttributeName);

                                    #endregion
                                }
                                else
                                {
                                    #region This is the last unknown attribute and with this, it is an undefined attribute

                                    UndefinedAttribute = typeOrAttr.TypeOrAttributeName;

                                    if (myListOfReferences.Count != 1)
                                    {
                                        throw new AmbiguousVertexAttributeException("The attribute or type \"" + typeOrAttr.TypeOrAttributeName + "\" has been used ambigous.");
                                    }
                                    else
                                    {
                                        var theRef = myListOfReferences.First();
                                        _Reference     = new Tuple <string, IVertexType>(theRef.Key, theRef.Value); //T1 -->key in context dictionary
                                        _LastType      = _Reference.Item2;
                                        _LastAttribute = new UnstructuredProperty(UndefinedAttribute);

                                        typeOrAttr.TypeAttribute = _LastAttribute;
                                        typeOrAttr.DBType        = _LastType;

                                        AddNewEdgeKey(_LastType, _LastAttribute.ID);
                                    }

                                    #endregion
                                }

                                //_isValidated = false;

                                //_invalidNodeParts.AddRange(parseNode.ChildNodes);

                                #endregion
                            }

                            #endregion
                        }

                        #endregion
                    }
                    else
                    {
                        #region This is a regular attribute after a reference (U.Name)

                        typeOrAttr.DBType        = _LastType;
                        typeOrAttr.TypeAttribute = typeOrAttr.DBType.GetAttributeDefinition(typeOrAttr.TypeOrAttributeName);
                        _LastAttribute           = typeOrAttr.TypeAttribute;

                        if (_LastAttribute == null)
                        {
                            if (curPart.Next != null || !allowUndefinedAttributes)
                            {
                                #region Calling an attribute on an undefined attribute is not allowed - so we assume a typo

                                throw new VertexAttributeIsNotDefinedException(typeOrAttr.TypeOrAttributeName);
                                //continue;

                                #endregion
                            }
                            else
                            {
                                UndefinedAttribute       = typeOrAttr.TypeOrAttributeName;
                                _LastAttribute           = new UnstructuredProperty(UndefinedAttribute);
                                typeOrAttr.TypeAttribute = _LastAttribute;
                                AddNewEdgeKey(_LastType, _LastAttribute.ID);
                            }
                        }
                        else
                        {
                            AddNewEdgeKey(_LastType, _LastAttribute.ID);
                        }

                        #endregion
                    }

                    #endregion

                    funcWorkingBase = _LastAttribute;
                }

                curPart = curPart.Next;

                #endregion
            }

            LevelKey = new LevelKey(Edges, myGraphDB, mySecurityToken, myTransactionToken);
        }
Ejemplo n.º 36
0
        internal void ConvertToAttributeType(GQLPluginManager myPluginManager, IAttributeDefinition typeAttribute, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            var newTuple = new List <TupleElement>();

            for (int i = 0; i < TupleElements.Count; i++)
            {
                var tupleElement = TupleElements[i].Value;

                if (tupleElement is SelectDefinition)
                {
                    #region partial select

                    var selectManager = new SelectManager(myGraphDB, myPluginManager);

                    var          selectDefinition = (tupleElement as SelectDefinition);
                    IQueryResult qresult          = selectManager.ExecuteSelect(mySecurityToken, myTransactionToken, selectDefinition, String.Empty);
                    if (qresult.Error != null)
                    {
                        throw qresult.Error;
                    }

                    IAttributeDefinition curAttr = ((tupleElement as SelectDefinition).SelectedElements.First().Item1 as IDChainDefinition).LastAttribute;

                    foreach (var _Vertex in qresult.Vertices)
                    {
                        if (!(_Vertex.HasProperty(curAttr.Name)))
                        {
                            continue;
                        }

                        if (curAttr != null)
                        {
                            var val = new ValueDefinition(_Vertex.GetProperty <Object>(curAttr.Name));
                            newTuple.Add(new TupleElement(val));
                        }
                        else
                        {
                            throw new NotImplementedQLException("");
                        }
                    }

                    #endregion
                }
                else if (TupleElements[i].Value is ValueDefinition)
                {
                    newTuple.Add(new TupleElement(new ValueDefinition((TupleElements[i].Value as ValueDefinition).Value)));
                }
                else
                {
                    throw new InvalidTupleException(TupleElements[i].Value.GetType().Name);
                }
            }

            TupleElements = newTuple;
        }
Ejemplo n.º 37
0
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition,
                                               Object myCallingObject,
                                               IVertex myDBObject,
                                               IGraphDB myGraphDB,
                                               SecurityToken mySecurityToken,
                                               Int64 myTransactionToken,
                                               params FuncParameter[] myParams)
        {
            #region initialisation

            List <TypeWithProperty> ObjectList = new List <TypeWithProperty>();

            var str    = myParams[0].Value.ToString();
            var method = Convert.ToBoolean(myParams[1].Value);

            if (str == "")
            {
                throw new InvalidFunctionParameterException("Input String", "Input String is leer", "null");
            }

            ObjectList = new TypeWithProperty().StringParser(str, myGraphDB, mySecurityToken, myTransactionToken);

            if (ObjectList.Count < 2)
            {
                throw new InvalidFunctionParameterException("Input String", "Input String has insufficient quantity objects", "null");
            }

            List <Tuple <double, List <Tuple <long, long> >, IVertexType, IVertexType> > all     = new List <Tuple <double, List <Tuple <long, long> >, IVertexType, IVertexType> >();
            Dictionary <Tuple <long, long>, List <List <Tuple <long, long> > > >         allPath = new Dictionary <Tuple <long, long>, List <List <Tuple <long, long> > > >();
            #endregion
            #region search Path between two any VertexTypes
            foreach (TypeWithProperty vertexStart in ObjectList)
            {
                foreach (TypeWithProperty vertexEnd in ObjectList)
                {
                    if (vertexStart != vertexEnd && vertexStart.Type.ID != vertexEnd.Type.ID)
                    {
                        if (method)
                        {
                            var output = this.ShortPath(vertexStart.Type, vertexEnd.Type);
                            if (output != null)
                            {
                                all.Add(output);
                            }
                        }
                        else
                        {
                            List <Tuple <long, long> > value = new List <Tuple <long, long> >();
                            value.Add(Tuple.Create(vertexStart.Type.ID, 0L));
                            this.DFS(vertexStart.Type, vertexEnd.Type, value);
                        }
                    }
                }
            }
            #endregion


            if (!method)
            {
                #region DFS
                #region path->allPath->PATH for better representation
                foreach (List <Tuple <long, long> > value in _path)
                {
                    if (!allPath.ContainsKey(Tuple.Create(value.First().Item1, value.Last().Item1)))
                    {
                        List <List <Tuple <long, long> > > temp = new List <List <Tuple <long, long> > >();
                        temp.Add(value);
                        allPath.Add(Tuple.Create(value.First().Item1, value.Last().Item1), temp);
                    }
                    else
                    {
                        allPath[Tuple.Create(value.First().Item1, value.Last().Item1)].Add(value);
                    }
                }

                List <List <Tuple <long, long> > > PATH = new List <List <Tuple <long, long> > >();

                foreach (KeyValuePair <Tuple <long, long>, List <List <Tuple <long, long> > > > value in allPath)
                {
                    var paths = value.Value;
                    foreach (List <Tuple <long, long> > abc in paths)
                    {
                        PATH.Add(abc);
                    }
                }

                if (PATH.Count < 1)
                {
                    throw new InvalidFunctionParameterException("PATH", "PATH with DFS not found", "null");
                }

                #endregion
                #region all paths merge
                foreach (KeyValuePair <Tuple <long, long>, List <List <Tuple <long, long> > > > value in allPath)
                {
                    var paths = value.Value;
                    foreach (List <Tuple <long, long> > abc in paths)
                    {
                        var flag_ends = false;
                        var iCount    = 0;
                        do
                        {
                            if (PATH.Count > 0)
                            {
                                var detekt = (PATH[iCount].Where(x => x.Item1 == value.Key.Item1).Count() > 0) && (PATH[iCount].Where(x => x.Item1 == value.Key.Item2).Count() > 0);                                 //PATH[iCount].Contains(value.Key.Item2);

                                if (!detekt)
                                {
                                    var test = 0;
                                    foreach (long wert in ObjectList.Select(x => x.Type.ID))
                                    {
                                        if (PATH[iCount].Where(x => x.Item1 == wert).Count() > 0)
                                        {
                                            test++;
                                        }
                                    }


                                    if (test == ObjectList.Count)
                                    {
                                        flag_ends = true;
                                    }
                                    else
                                    {
                                        if (PATH[iCount].Contains(abc.Where(x => x.Item2 == 0).First()))
                                        {
                                            PATH.Add(PATH[iCount].Union(abc).ToList());
                                        }
                                    }
                                }
                            }
                            else
                            {
                                flag_ends = true;
                            }
                            if (PATH.Count - 1 > iCount)
                            {
                                iCount++;
                            }
                            else
                            {
                                flag_ends = true;
                            }
                        }while (!flag_ends);
                    }
                }

                #endregion
                #region redundance kill zone


                var jCount     = 0;
                var flag_ends2 = false;
                do
                {
                    var test = 0;
                    test = 0;
                    foreach (long value in ObjectList.Select(x => x.Type.ID))
                    {
                        if (PATH[jCount].Where(x => x.Item1 == value).Count() > 0)
                        {
                            test++;
                        }
                    }


                    if (test < ObjectList.Count)
                    {
                        PATH.Remove(PATH[jCount]);
                        if (PATH.Count == 0 || PATH.Count == jCount)
                        {
                            flag_ends2 = true;
                        }
                    }
                    else
                    {
                        if (PATH.Count - 1 > jCount)
                        {
                            jCount++;
                        }
                        else
                        {
                            flag_ends2 = true;
                        }
                    }
                }while (!flag_ends2);

                flag_ends2 = false;
                var iCount2 = 0;
                do
                {
                    List <List <Tuple <long, long> > > delete = new List <List <Tuple <long, long> > >();

                    foreach (List <Tuple <long, long> > wert in PATH)
                    {
                        var flag    = true;
                        var flagEnd = true;
                        var jCountB = 0;
                        if (PATH[iCount2].Count == wert.Count)
                        {
                            do
                            {
                                if (!wert.Contains(PATH[iCount2][jCountB]))
                                {
                                    flag    = false;
                                    flagEnd = false;
                                }

                                if (PATH[iCount2].Count - 1 > jCountB)
                                {
                                    jCountB++;
                                }
                                else
                                {
                                    flagEnd = false;
                                }
                            }while (flagEnd);
                            if (flag)
                            {
                                if (flag && !PATH[iCount2].Equals(wert))
                                {
                                    delete.Add(wert);
                                }
                            }
                        }
                    }

                    if (delete.Count > 0)                    //(test > 1)
                    {
                        foreach (List <Tuple <long, long> > value in delete)
                        {
                            PATH.Remove(value);
                        }
                        if (PATH.Count == 0 || PATH.Count == iCount2)
                        {
                            flag_ends2 = true;
                        }
                    }
                    else
                    {
                        if (PATH.Count - 1 > iCount2)
                        {
                            iCount2++;
                        }
                        else
                        {
                            flag_ends2 = true;
                        }
                    }
                }while (!flag_ends2);

                if (PATH.Count < 1)
                {
                    throw new InvalidFunctionParameterException("PATH", "PATH with DFS not found", "null");
                }

                var minPATH   = PATH.Min(x => x.Count);
                var indexPATH = PATH.First(x => x.Count == minPATH);
                this.Helper(myGraphDB, mySecurityToken, myTransactionToken, ObjectList, indexPATH);
            }
            #endregion
            #endregion
            else
            {
                #region Dijkstra
                #region all shortest paths between two any VertexTypes to PATHShort for better representation
                List <List <Tuple <long, long> > > PATHShort = new List <List <Tuple <long, long> > >();

                foreach (Tuple <double, List <Tuple <long, long> >, IVertexType, IVertexType> value in all)
                {
                    PATHShort.Add(value.Item2);
                }
                if (PATHShort.Count < 1)
                {
                    throw new InvalidFunctionParameterException("PATH", "PATH with Dijkstra not found", "null");
                }

                #endregion
                #region shortest paths merge

                foreach (Tuple <double, List <Tuple <long, long> >, IVertexType, IVertexType> value in all)
                {
                    var abc = value.Item2;

                    bool flag_ends = false;
                    int  iCount    = 0;
                    do
                    {
                        if (PATHShort.Count > 0)
                        {
                            var detekt = (PATHShort[iCount].Where(x => x.Item1 == value.Item3.ID).Count() > 0) && (PATHShort[iCount].Where(x => x.Item1 == value.Item4.ID).Count() > 0);                             //PATH[iCount].Contains(value.Key.Item2);

                            if (!detekt)
                            {
                                var test = 0;
                                foreach (long wert in ObjectList.Select(x => x.Type.ID))
                                {
                                    if (PATHShort[iCount].Where(x => x.Item1 == wert).Count() > 0)
                                    {
                                        test++;
                                    }
                                }


                                if (test == ObjectList.Count)
                                {
                                    flag_ends = true;
                                }
                                else
                                {
                                    if (PATHShort[iCount].Contains(abc.Where(x => x.Item2 == 0).First()))
                                    {
                                        PATHShort.Add(PATHShort[iCount].Union(abc).ToList());
                                    }
                                }
                            }
                        }
                        else
                        {
                            flag_ends = true;
                        }
                        if (PATHShort.Count - 1 > iCount)
                        {
                            iCount++;
                        }
                        else
                        {
                            flag_ends = true;
                        }
                    }while (!flag_ends);
                }
                #endregion
                #region redudance kill zone for shortest paths
                var jCount     = 0;
                var flag_ends2 = false;
                do
                {
                    var test = 0;
                    test = 0;
                    foreach (long value in ObjectList.Select(x => x.Type.ID))
                    {
                        if (PATHShort[jCount].Where(x => x.Item1 == value).Count() > 0)
                        {
                            test++;
                        }
                    }


                    if (test < ObjectList.Count)
                    {
                        PATHShort.Remove(PATHShort[jCount]);
                        if (PATHShort.Count == 0 || PATHShort.Count == jCount)
                        {
                            flag_ends2 = true;
                        }
                    }
                    else
                    {
                        if (PATHShort.Count - 1 > jCount)
                        {
                            jCount++;
                        }
                        else
                        {
                            flag_ends2 = true;
                        }
                    }
                }while (!flag_ends2);


                flag_ends2 = false;
                var iCount2 = 0;
                do
                {
                    List <List <Tuple <long, long> > > delete = new List <List <Tuple <long, long> > >();
                    foreach (List <Tuple <long, long> > wert in PATHShort)
                    {
                        var flag    = true;
                        var flagEnd = true;
                        var jCountB = 0;
                        if (PATHShort[iCount2].Count == wert.Count)
                        {
                            do
                            {
                                if (!wert.Contains(PATHShort[iCount2][jCountB]))
                                {
                                    flag    = false;
                                    flagEnd = false;
                                }

                                if (PATHShort[iCount2].Count - 1 > jCountB)
                                {
                                    jCountB++;
                                }
                                else
                                {
                                    flagEnd = false;
                                }
                            }while (flagEnd);
                            if (flag && !PATHShort[iCount2].Equals(wert))
                            {
                                delete.Add(wert);
                            }
                        }
                    }
                    if (delete.Count > 0)                    //(test > 1)
                    {
                        foreach (List <Tuple <long, long> > value in delete)
                        {
                            PATHShort.Remove(value);
                        }
                        if (PATHShort.Count == 0 || PATHShort.Count == iCount2)
                        {
                            flag_ends2 = true;
                        }
                    }
                    else
                    {
                        if (PATHShort.Count - 1 > iCount2)
                        {
                            iCount2++;
                        }
                        else
                        {
                            flag_ends2 = true;
                        }
                    }
                }while (!flag_ends2);

                if (PATHShort.Count < 1)
                {
                    throw new InvalidFunctionParameterException("PATH", "PATH with Dijkstra not found", "null");
                }

                var minPATHShort   = PATHShort.Min(x => x.Count);
                var indexPATHShort = PATHShort.First(x => x.Count == minPATHShort);
                this.Helper(myGraphDB, mySecurityToken, myTransactionToken, ObjectList, indexPATHShort);
            }
            #endregion
            #endregion
            #region Output


            var result = new ListCollectionWrapper(_stringPath.Select(x => x.Item1 + " = " + x.Item2));
            this._path.Clear();
            this._stringPath.Clear();
            return(new FuncParameter(result));

            #endregion
        }
Ejemplo n.º 38
0
        public virtual FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, params FuncParameter[] myParams)
        {
            Boolean containsVariableNumOfParams = Parameters.Exists(p => p.VariableNumOfParams);

            #region check number of parameters

            if (Parameters.Count != myParams.Length && (!containsVariableNumOfParams))
            {
                throw new FunctionParameterCountMismatchException(this.PluginName, Parameters.Count, myParams.Length);
            }
            else if (containsVariableNumOfParams && myParams.Length == 0)
            {
                throw new FunctionParameterCountMismatchException(this.PluginName, Parameters.Count, myParams.Length);
            }

            #endregion

            #region check parameter types

            Int32 definedParamCounter = 0;
            for (Int32 i = 0; i < myParams.Count(); i++)
            {
                if (Parameters[definedParamCounter].Value.GetType() != ((FuncParameter)myParams[i]).Value.GetType())
                {
                    throw new FunctionParameterTypeMismatchException(Parameters[definedParamCounter].Value.GetType(), myParams[i].GetType());
                }

                if (!Parameters[definedParamCounter].VariableNumOfParams)
                {
                    definedParamCounter++;
                }
            }

            #endregion

            return(null);
        }
Ejemplo n.º 39
0
 /// <summary>
 /// This will validate the function to a working base.
 /// </summary>
 /// <param name="workingBase">The working base. Might be null for type independent function calls like CURRENTDATE().</param>
 /// <param name="typeManager"></param>
 /// <returns></returns>
 public abstract bool ValidateWorkingBase(Object myWorkingBase, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken);
Ejemplo n.º 40
0
        public BinaryExpressionDefinition GetBinaryExpression(GQLPluginManager myPluginManager, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            AExpressionDefinition right;
            var op = GetOperatorBySymbol(_OperatorSymbol);

            if (op == null)
            {
                throw new OperatorDoesNotExistException(_OperatorSymbol);
            }

            right = new ValueDefinition(1);

            var binExpr = new BinaryExpressionDefinition("*", _Expression, right);

            binExpr.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);

            return(binExpr);
        }
Ejemplo n.º 41
0
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, params FuncParameter[] myParams)
        {
            StringBuilder resString = new StringBuilder();

            if (myCallingObject != null)
            {
                if (myCallingObject is string)
                {
                    resString.Append(myCallingObject as String);
                }
            }

            foreach (FuncParameter fp in myParams)
            {
                resString.Append(fp.Value.ToString());
            }

            return(new FuncParameter(resString.ToString()));
        }
Ejemplo n.º 42
0
 public override bool ValidateWorkingBase(Object myWorkingBase, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
 {
     return(myWorkingBase == null);
 }
Ejemplo n.º 43
0
        public override IEnumerable <IVertexView> GetResult(
            GQLPluginManager myPluginManager,
            IGraphDB myGraphDB,
            SecurityToken mySecurityToken,
            Int64 myTransactionToken)
        {
            var resultingVertices = new List <IVertexView>();

            if (!String.IsNullOrEmpty(_FuncName))
            {
                #region Specific function

                //aggregate is user defined z.b. sones.exist or another.exist
                if (_FuncName.Contains("."))
                {
                    //get plugin
                    var func = myPluginManager.GetAndInitializePlugin <IGQLFunction>(_FuncName);

                    if (func != null)
                    {
                        resultingVertices = new List <IVertexView>()
                        {
                            GenerateOutput(func, _FuncName)
                        };
                    }
                    else
                    {
                        throw new AggregateOrFunctionDoesNotExistException(typeof(IGQLFunction), _FuncName, "");
                    }
                }
                //try get function
                else
                {
                    try
                    {
                        //get plugin
                        var func = myPluginManager.GetAndInitializePlugin <IGQLFunction>(_FuncName);

                        if (func != null)
                        {
                            resultingVertices = new List <IVertexView>()
                            {
                                GenerateOutput(func, _FuncName)
                            };
                        }
                        else
                        {
                            throw new AggregateOrFunctionDoesNotExistException(typeof(IGQLFunction), _FuncName, "");
                        }
                    }
                    catch (ASonesException e)
                    {
                        //maybe user forgot prefix 'sones.'
                        //get plugin
                        var func = myPluginManager.GetAndInitializePlugin <IGQLFunction>("SONES." + _FuncName);

                        if (func != null)
                        {
                            resultingVertices = new List <IVertexView>()
                            {
                                GenerateOutput(func, "SONES." + _FuncName)
                            };
                        }
                        else
                        {
                            throw new AggregateOrFunctionDoesNotExistException(typeof(IGQLFunction), _FuncName, "");
                        }
                    }
                }

                #endregion
            }

            else
            {
                #region All functions

                myPluginManager.GetPluginNameForType <IGQLFunction>();
                foreach (var funcName in myPluginManager.GetPluginNameForType <IGQLFunction>())
                {
                    //get plugin
                    var func = myPluginManager.GetAndInitializePlugin <IGQLFunction>(funcName);

                    if (func != null)
                    {
                        resultingVertices.Add(GenerateOutput(func, funcName));
                    }
                    else
                    {
                        throw new AggregateOrFunctionDoesNotExistException(typeof(IGQLFunction), funcName, "");
                    }
                }

                #endregion
            }

            return(resultingVertices);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Checks if there is a valid tuple node. Valid tuple nodes in this case look like : (Name = 'Henning', Age = 10)
        /// </summary>
        /// <param name="tupleElementList">List of tuple elements</param>
        /// <param name="myAttributes">myAttributes of the type</param>
        /// <returns>True if valid or otherwise false</returns>
        internal bool IsValidTupleNode(List <TupleElement> tupleElementList, IVertexType myGraphType, GQLPluginManager myPluginManager, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            foreach (TupleElement aTupleElement in tupleElementList)
            {
                if (aTupleElement.Value is BinaryExpressionDefinition)
                {
                    ((BinaryExpressionDefinition)aTupleElement.Value).Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, myGraphType);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 45
0
        public IEnumerable <IVertexView> Import(string myLocation,
                                                IGraphDB myGraphDB,
                                                IGraphQL myGraphQL,
                                                SecurityToken mySecurityToken,
                                                Int64 myTransactionToken,
                                                UInt32 myParallelTasks          = 1U,
                                                IEnumerable <string> myComments = null,
                                                UInt64?myOffset = null,
                                                UInt64?myLimit  = null,
                                                VerbosityTypes myVerbosityTypes       = VerbosityTypes.Silent,
                                                Dictionary <string, string> myOptions = null)
        {
            #region data

            if (myGraphDB == null)
            {
                throw new UnknownException(new ArgumentNullException("Missing GraphDB object"));
            }

            if (myLocation == null)
            {
                throw new UnknownException(new ArgumentNullException("Missing Location object"));
            }

//			if(mySecurityToken == null)
//			{
//				return new QueryResult("",
//						ImportFormat,
//						0,
//						ResultType.Failed,
//						null,
//						new UnknownException(new ArgumentNullException("mySecurityToken")));
//			}
//			if(myTransactionToken == null)
//			{
//				return new QueryResult("",
//						ImportFormat,
//						0,
//						ResultType.Failed,
//						null,
//						new UnknownException(new ArgumentNullException("myTransactionToken")));
//			}

            if (myOptions == null)
            {
                throw new UnknownException(
                          new ArgumentNullException(
                              String.Format("Missing Options {0}, {1}",
                                            PARAM_VERTEXTYPENAME,
                                            PARAM_EDGENAME
                                            )));
            }

            _GraphDB          = myGraphDB;
            _SecurityToken    = mySecurityToken;
            _TransactionToken = myTransactionToken;
            InitVertexSettings(myOptions);

            var    sw     = new Stopwatch();
            Stream stream = null;

            #endregion

            #region create vertex type

            CreateVertexType();

            #endregion

            #region import

            lock (_Lock)
            {
                #region read elements

                try
                {
                    if (myLocation.ToLower().StartsWith("file://") || myLocation.ToLower().StartsWith("file:\\"))
                    {
                        stream = GetStreamFromFile(myLocation.Substring("file://".Length));
                    }
                    else if (myLocation.StartsWith("http://"))
                    {
                        stream = GetStreamFromHttp(myLocation);
                    }
                    else
                    {
                        throw new FormatException("Given file location is invalid.");
                    }

                    var reader = XmlReader.Create(stream);

                    sw.Start();

                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            switch (reader.Name)
                            {
                            case GraphMLTokens.GRAPHML:
                                break;

                            case GraphMLTokens.GRAPH:
                                break;

                            case GraphMLTokens.KEY:
                                ReadAttributeDefinition(reader);
                                break;

                            case GraphMLTokens.VERTEX:
                                ReadVertex(reader);
                                break;

                            case GraphMLTokens.EDGE:
                                ReadEdge(reader);
                                break;

                            default:
                                throw new XmlException(String.Format("Unsupported Node Type in GraphML File: {0}",
                                                                     reader.Name));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // drop vertex type in case of exception
                    DropVertexType();

                    throw;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                    sw.Stop();
                }

                #endregion
            }

            #endregion

            return(null);
        }
Ejemplo n.º 46
0
        /// <summary>
        /// returns a list of guids which match the tupleNode of the ListOfDBObjects object.
        /// </summary>
        public IEnumerable <Tuple <IVertex, Dictionary <String, object> > > GetCorrespondigDBObjectUUIDAsList(IVertexType myType, IVertexType validationType, GQLPluginManager myPluginManager, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            #region Evaluate tuple

            //ask guid-index of type
            foreach (TupleElement aTupleElement in TupleElements)
            {
                if (aTupleElement.Value is BinaryExpressionDefinition)
                {
                    #region Binary Expression

                    var aUniqueExpr = (BinaryExpressionDefinition)aTupleElement.Value;

                    aUniqueExpr.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, validationType);

                    var _graphResult = aUniqueExpr.Calculon(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, new CommonUsageGraph(myGraphDB, mySecurityToken, myTransactionToken));

                    foreach (var aDBO in _graphResult.Select(new LevelKey(validationType.ID, myGraphDB, mySecurityToken, myTransactionToken), null, true))
                    {
                        yield return(new Tuple <IVertex, Dictionary <String, object> >(aDBO, aTupleElement.Parameters));
                    }

                    #endregion
                }
                else
                {
                    #region tuple node

                    if (aTupleElement.Value is TupleDefinition)
                    {
                        var aTupleNode = (TupleDefinition)aTupleElement.Value;

                        if (IsValidTupleNode(aTupleNode.TupleElements, myType, myPluginManager, myGraphDB, mySecurityToken, myTransactionToken))
                        {
                            #region get partial results

                            BinaryExpressionDefinition tempNode = null;

                            foreach (TupleElement aElement in aTupleNode)
                            {
                                tempNode = (BinaryExpressionDefinition)aElement.Value;

                                ValidateBinaryExpression(tempNode, validationType, myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);

                                var tempGraphResult = tempNode.Calculon(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, new CommonUsageGraph(myGraphDB, mySecurityToken, myTransactionToken));

                                foreach (var aDBO in tempGraphResult.Select(new LevelKey(validationType.ID, myGraphDB, mySecurityToken, myTransactionToken), null, true))
                                {
                                    yield return(new Tuple <IVertex, Dictionary <String, object> >(aDBO, aTupleElement.Parameters));
                                }
                            }

                            #endregion
                        }
                    }
                    #endregion
                }
            }

            #endregion

            yield break;
        }
Ejemplo n.º 47
0
        private readonly Dictionary <String, IUsageDataCollector> _usagedatacollectors; // Usage Data Collector

        #endregion

        #region Constructor

        /// <summary>
        /// The GraphDS server constructor.
        /// </summary>
        /// <param name="myGraphDB">The graph db instance.</param>
        /// <param name="myIPAddress">the IP adress this GraphDS Server should bind itself to</param>
        /// <param name="myPort">the port this GraphDS Server should listen on</param>
        /// <param name="PluginDefinitions">the plugins that shall be loaded and their according parameters</param>
        public GraphDS_Server(IGraphDB myGraphDB, GraphDSPlugins Plugins = null)
        {
            _iGraphDB            = myGraphDB;
            _pluginManager       = new GraphDSPluginManager();
            _ID                  = new Guid();
            _QueryLanguages      = new Dictionary <string, IGraphQL>();
            _DrainPipes          = new Dictionary <string, IDrainPipe>();
            _graphDSServices     = new Dictionary <String, IService>();
            _usagedatacollectors = new Dictionary <string, IUsageDataCollector>();
            _plugins             = Plugins;

            #region Load Configured Plugins

            if (_plugins == null)
            {
                #region set the defaults
                // which are:
                //  GQL with GraphDB Parameter
                #region GQL
                List <PluginDefinition>     QueryLanguages = new List <PluginDefinition>();
                Dictionary <string, object> GQL_Parameters = new Dictionary <string, object>();
                GQL_Parameters.Add("GraphDB", myGraphDB);

                QueryLanguages.Add(new PluginDefinition("sones.gql", GQL_Parameters));
                #endregion

                _plugins = new GraphDSPlugins(QueryLanguages, null);
                #endregion
            }

            // now at least the default plugins or a user setup is stored in the _plugins structure
            // iterate through and instantiate if found
            #region IGraphQL Plugins
            if (_plugins.IGraphQLPlugins != null)
            {
                // we got QL
                foreach (PluginDefinition _pd in _plugins.IGraphQLPlugins)
                {
                    // load!
                    IGraphQL loaded = LoadIGraphQLPlugins(_pd);

                    // add!
                    if (loaded != null)
                    {
                        _QueryLanguages.Add(_pd.NameOfPlugin, loaded);
                    }
                    //                    else
                    //                        System.Diagnostics.Debug.WriteLine("Could not load plugin " + _pd.NameOfPlugin);
                }
            }
            #endregion

            #region IDrainPipe Plugins
            if (_plugins.IDrainPipePlugins != null)
            {
                // we got IDrainPipePlugins
                foreach (PluginDefinition _pd in _plugins.IDrainPipePlugins)
                {
                    // load!
                    IDrainPipe loaded = LoadIDrainPipes(_pd);
                    // add!
                    if (loaded != null)
                    {
                        _DrainPipes.Add(_pd.NameOfPlugin, loaded);
                    }
                    //                    else
                    //                        System.Diagnostics.Debug.WriteLine("Could not load plugin " + _pd.NameOfPlugin);
                }
            }
            #endregion

            #region IUsageDataCollector Plugins
            if (_plugins.IUsageDataCollectorPlugIns != null)
            {
                // we got IUsageDataCollector
                foreach (PluginDefinition _pd in _plugins.IUsageDataCollectorPlugIns)
                {
                    // load!
                    IUsageDataCollector loaded = LoadIUsageDataCollector(_pd);
                    // add!
                    if (loaded != null)
                    {
                        _usagedatacollectors.Add(_pd.NameOfPlugin, loaded);
                    }
                }
            }
            #endregion

            #endregion
        }
Ejemplo n.º 48
0
        public List <FuncParameter> Execute(IVertexType myTypeOfDBObject, IVertex myDBObject, String myReference, GQLPluginManager myPluginManager, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            List <FuncParameter> evaluatedParams = new List <FuncParameter>();
            int           paramCounter           = 0;
            FuncParameter validationOutput;

            //ParameterValue currentParameter;

            for (int i = 0; i < Parameters.Count; i++)
            {
                ParameterValue currentParameter = Function.GetParameter(paramCounter);

                if (Parameters[i] is BinaryExpressionDefinition)
                {
                    ((BinaryExpressionDefinition)Parameters[i]).Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);

                    #region handle BinExp

                    var calculatedGraphResult = ((BinaryExpressionDefinition)Parameters[i]).Calculon(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, new CommonUsageGraph(myGraphDB, mySecurityToken, myTransactionToken));

                    var extractedDBOs = calculatedGraphResult.Select(new LevelKey(myTypeOfDBObject.ID, myGraphDB, mySecurityToken, myTransactionToken), null, true);

                    #region validation

                    validationOutput = ValidateAndAddParameter(currentParameter, extractedDBOs, null);

                    evaluatedParams.Add(validationOutput);

                    #endregion

                    #endregion
                }
                else
                {
                    if (Parameters[i] is IDChainDefinition)
                    {
                        #region handle IDNode

                        var tempIDChain = (IDChainDefinition)Parameters[i];

                        tempIDChain.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, false);

                        if (currentParameter.Value is IAttributeDefinition)
                        {
                            #region validation

                            validationOutput = ValidateAndAddParameter(currentParameter, tempIDChain.LastAttribute, null);

                            evaluatedParams.Add(validationOutput);

                            #endregion
                        }
                        else
                        {
                            if ((tempIDChain.LastAttribute == null) && (tempIDChain.SelectType != TypesOfSelect.None))
                            {
                                #region IDNode with asterisk

                                #region validation

                                validationOutput = ValidateAndAddParameter(currentParameter, tempIDChain, null);

                                evaluatedParams.Add(validationOutput);

                                #endregion

                                #endregion
                            }
                            else
                            {
                                switch (tempIDChain.LastAttribute.Kind)
                                {
                                case AttributeType.Property:

                                    #region Property

                                    IPropertyDefinition propertyDefinition = (IPropertyDefinition)tempIDChain.LastAttribute;

                                    IComparable value = null;

                                    if (myDBObject.HasProperty(propertyDefinition.ID))
                                    {
                                        value = propertyDefinition.GetValue(myDBObject);
                                    }

                                    #region validation

                                    validationOutput = ValidateAndAddParameter(currentParameter, value, tempIDChain.LastAttribute);

                                    evaluatedParams.Add(validationOutput);

                                    #endregion

                                    #endregion
                                    break;

                                case AttributeType.IncomingEdge:

                                    #region IncomingEdge

                                    IIncomingEdgeDefinition incomingEdgeAttribute = (IIncomingEdgeDefinition)tempIDChain.LastAttribute;

                                    IEnumerable <IVertex> dbos = new List <IVertex>();

                                    if (myDBObject.HasIncomingVertices(incomingEdgeAttribute.RelatedEdgeDefinition.SourceVertexType.ID, incomingEdgeAttribute.RelatedEdgeDefinition.ID))
                                    {
                                        dbos = myDBObject.GetIncomingVertices(incomingEdgeAttribute.RelatedEdgeDefinition.SourceVertexType.ID, incomingEdgeAttribute.RelatedEdgeDefinition.ID);
                                    }

                                    #region validation

                                    validationOutput = ValidateAndAddParameter(currentParameter, dbos, tempIDChain.LastAttribute);

                                    evaluatedParams.Add(validationOutput);

                                    #endregion

                                    #endregion
                                    break;

                                case AttributeType.OutgoingEdge:

                                    #region outgoing Edge

                                    IOutgoingEdgeDefinition outgoingEdgeAttribute = (IOutgoingEdgeDefinition)tempIDChain.LastAttribute;

                                    IEnumerable <IVertex> outgoingDBOs = new List <IVertex>();

                                    if (myDBObject.HasOutgoingEdge(outgoingEdgeAttribute.ID))
                                    {
                                        outgoingDBOs = myDBObject.GetOutgoingEdge(outgoingEdgeAttribute.ID).GetTargetVertices();
                                    }

                                    #region validation

                                    validationOutput = ValidateAndAddParameter(currentParameter, outgoingDBOs, tempIDChain.LastAttribute);

                                    evaluatedParams.Add(validationOutput);

                                    #endregion

                                    #endregion
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region any other

                        #region validation

                        validationOutput = ValidateAndAddParameter(currentParameter, Parameters[i], null);

                        evaluatedParams.Add(validationOutput);

                        #endregion

                        #endregion
                    }
                }

                #region increase parameter counter

                if (!currentParameter.VariableNumOfParams)
                {
                    paramCounter++;
                }

                #endregion
            }


            return(evaluatedParams);
        }
Ejemplo n.º 49
0
 //Ctor
 public SocialPostManager()
 {
     _graphDB = new Neo4jDB();
 }
Ejemplo n.º 50
0
 public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, params FuncParameter[] myParams)
 {
     if (myCallingObject is String)
     {
         return(new FuncParameter((myCallingObject as String).ToString().ToUpper()));
     }
     else
     {
         throw new FunctionParameterTypeMismatchException(typeof(String), myCallingObject.GetType());
     }
 }
Ejemplo n.º 51
0
        protected void ValidateBinaryExpression(BinaryExpressionDefinition aUniqueExpr, IVertexType validationType, GQLPluginManager myPluginManager, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            switch (aUniqueExpr.TypeOfBinaryExpression)
            {
            case TypesOfBinaryExpression.LeftComplex:
                ValidateBinaryExpressionInternal(aUniqueExpr.Left, validationType, myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);

                break;

            case TypesOfBinaryExpression.RightComplex:
                ValidateBinaryExpressionInternal(aUniqueExpr.Right, validationType, myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);

                break;

            case TypesOfBinaryExpression.Complex:
                ValidateBinaryExpressionInternal(aUniqueExpr.Left, validationType, myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);
                ValidateBinaryExpressionInternal(aUniqueExpr.Right, validationType, myPluginManager, myGraphDB, mySecurityToken, myTransactionToken);

                break;

            case TypesOfBinaryExpression.Atom:
            default:
                break;
            }
        }
Ejemplo n.º 52
0
 public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, params FuncParameter[] myParams)
 {
     return(new FuncParameter(DateTime.Now));
 }
Ejemplo n.º 53
0
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition,
                                               Object myCallingObject,
                                               IVertex myStartVertex,
                                               IGraphDB myGraphDB,
                                               SecurityToken mySecurityToken,
                                               Int64 myTransactionToken,
                                               params FuncParameter[] myParams)
        {
            #region initialize data

            var graph = myGraphDB;


            // The edge we starting of (e.g. Friends)
            var typeAttribute = myAttributeDefinition;

            if (myStartVertex == null)
            {
                throw new InvalidFunctionParameterException("StartVertex", "Vertex that represents the start vertex", "null");
            }

            //set the start node
            var startNode = myStartVertex;

            if ((myParams[0].Value as IEnumerable <IVertex>) == null)
            {
                throw new InvalidFunctionParameterException("TargetVertex", "Set of vertices that represents the target vertices", "null");
            }

            //set the target node
            var targetNode = (myParams[0].Value as IEnumerable <IVertex>).First();


            //set the maximum depth
            UInt64 maxDepth = Convert.ToUInt64(myParams[1].Value);

            //set the maximum path length
            UInt64 maxPathLength = Convert.ToUInt64(myParams[2].Value);

            //mark if only the shortest path should be searched
            bool onlyShortestPath = Convert.ToBoolean(myParams[3].Value);

            //mark if all paths should be searched
            bool allPaths = Convert.ToBoolean(myParams[4].Value);

            if (!onlyShortestPath && !allPaths)
            {
                allPaths = true;
            }

            bool useBidirectionalBFS = false;

            if (myParams.GetLength(0) == 6)
            {
                //mark if the BidirectionalBFS should be used
                useBidirectionalBFS = Convert.ToBoolean(myParams[5].Value);
            }

            var vertexType = myGraphDB.GetVertexType <IVertexType>(mySecurityToken,
                                                                   myTransactionToken,
                                                                   new RequestGetVertexType(startNode.VertexTypeID),
                                                                   (stats, type) => type);

            if (vertexType == null)
            {
                throw new InvalidFunctionParameterException("StartVertexType",
                                                            "VertexType that represents the start vertex type not found",
                                                            startNode.VertexTypeID);
            }
            #endregion

            #region check correctness of parameters

            //check if values are correct
            if (maxDepth < 1)
            {
                throw new InvalidFunctionParameterException("maxDepth", ">= 1", maxDepth.ToString());
            }

            if (maxPathLength < 2)
            {
                throw new InvalidFunctionParameterException("maxPathLength", ">= 2", maxPathLength.ToString());
            }

            #endregion

            #region call graph function

            HashSet <List <Tuple <long, long> > > paths = null;

            //call BFS find methods
            if (useBidirectionalBFS)
            {
                paths = new BidirectionalBFS().Find(typeAttribute,
                                                    vertexType,
                                                    startNode,
                                                    targetNode,
                                                    onlyShortestPath,
                                                    allPaths,
                                                    maxDepth, maxPathLength);
            }
            else
            {
                paths = new BFS().Find(typeAttribute,
                                       vertexType,
                                       startNode,
                                       targetNode,
                                       onlyShortestPath,
                                       allPaths,
                                       maxDepth,
                                       maxPathLength);
            }

            #endregion

            #region create output

            if (paths != null)
            {
                #region create outputted views

                List <List <Tuple <long, long> > .Enumerator> enumerators = new List <List <Tuple <long, long> > .Enumerator>();

                foreach (var path in paths)
                {
                    enumerators.Add(path.GetEnumerator());
                }

                var view = GenerateVertexView(enumerators);

                #endregion

                return(new FuncParameter(view));
            }
            else
            {
                return(new FuncParameter(new VertexView(null, null)));
            }

            #endregion
        }
Ejemplo n.º 54
0
        private void ValidateBinaryExpressionInternal(AExpressionDefinition aUniqueExpr, IVertexType validationType, GQLPluginManager myPluginManager, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            if (aUniqueExpr is BinaryExpressionDefinition)
            {
                (aUniqueExpr as BinaryExpressionDefinition).Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, validationType);
            }
            else
            {
                var _potIdNode = aUniqueExpr as IDChainDefinition;

                if (_potIdNode != null)
                {
                    //var validationResult = _potIdNode.ValidateMe(validationType, typeManager);
                    _potIdNode.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, false, validationType);
                }
            }
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Extracts data for a binary expression
        /// </summary>
        /// <param name="myComplexValue">The complex part of the binary expression.</param>
        /// <param name="mySimpleValue">The simple/atomic part of the expression.</param>
        /// <param name="errors">The list of errors.</param>
        /// <param name="typeOfBinExpr">The kind of the binary expression</param>
        /// <returns>A data tuple.</returns>
        private static DataContainer ExtractData(AExpressionDefinition myComplexValue,
                                                 AExpressionDefinition mySimpleValue,
                                                 ref TypesOfBinaryExpression typeOfBinExpr,
                                                 GQLPluginManager myPluginManager,
                                                 IGraphDB myGraphDB,
                                                 SecurityToken mySecurityToken,
                                                 Int64 myTransactionToken,
                                                 Boolean aggregateAllowed)
        {
            #region data

            //the complex IDNode (sth. like U.Age or Count(U.Friends))
            IDChainDefinition complexIDNode = null;

            //the value that is on the opposite of the complex IDNode
            AExpressionDefinition simpleValue = null;

            //a complex IDNode may result in a complexValue (i.e. Count(U.Friends) --> 3)
            AExpressionDefinition complexValue = null;

            //reference to former myComplexValue
            AExpressionDefinition extraordinaryValue = null;

            #endregion

            #region extraction

            if (myComplexValue is IDChainDefinition)
            {
                #region IDNode

                #region Data

                complexIDNode = (IDChainDefinition)myComplexValue;
                complexIDNode.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, false);
                if (complexIDNode.Any(id => id is ChainPartFuncDefinition))
                {
                    if (complexIDNode.Edges == null || complexIDNode.Edges.Count == 0)
                    {
                        #region parameterless function

                        var fcn = (complexIDNode.First(id => id is ChainPartFuncDefinition) as ChainPartFuncDefinition);

                        // somes functions (aggregates) like SUM are not valid for where expressions, though they are not resolved
                        if (fcn.Function == null)
                        {
                            throw new FunctionDoesNotExistException(fcn.FuncName);
                        }

                        FuncParameter pResult = fcn.Function.ExecFunc(null, null, null, myGraphDB, mySecurityToken, myTransactionToken);

                        //simpleValue = new AtomValue(fcn.Function.TypeOfResult, ((FuncParameter)pResult.Value).Value); //the new simple value extraced from the function
                        simpleValue   = new ValueDefinition(((FuncParameter)pResult).Value);
                        typeOfBinExpr = TypesOfBinaryExpression.Unknown; //we do not know if we are left or right associated
                        complexIDNode = null;                            //we resolved it... so it's null

                        #endregion
                    }
                    else
                    {
                        //extraordinaryValue = (complexIDNode.First(id => id is ChainPartFuncDefinition) as ChainPartFuncDefinition);
                        extraordinaryValue = complexIDNode;

                        if (mySimpleValue is ValueDefinition)
                        {
                            simpleValue = mySimpleValue;
                        }
                    }
                }
                else
                {
                    if (mySimpleValue is ValueDefinition)
                    {
                        try
                        {
                            if (complexIDNode.IsUndefinedAttribute)
                            {
                                throw new VertexAttributeIsNotDefinedException(complexIDNode.UndefinedAttribute);
                            }

                            simpleValue = GetCorrectValueDefinition(complexIDNode.LastAttribute, complexIDNode.LastType, ((ValueDefinition)mySimpleValue));
                        }
                        catch (FormatException)
                        {
                            throw new DataTypeDoesNotMatchException(((IPropertyDefinition)complexIDNode.LastAttribute).BaseType.Name, ((ValueDefinition)mySimpleValue).Value.GetType().Name);
                        }
                    }
                    else
                    {
                        if (mySimpleValue is TupleDefinition)
                        {
                            ((TupleDefinition)mySimpleValue).ConvertToAttributeType(myPluginManager, complexIDNode.LastAttribute, myGraphDB, mySecurityToken, myTransactionToken);

                            simpleValue = mySimpleValue;
                        }
                    }
                }

                #endregion


                #endregion
            }
            else if (myComplexValue is TupleDefinition)
            {
                #region TupleSetNode

                complexValue  = ((TupleDefinition)myComplexValue);
                simpleValue   = mySimpleValue;
                typeOfBinExpr = TypesOfBinaryExpression.Atom;

                #endregion
            }
            else if (myComplexValue is AggregateDefinition)
            {
                #region AggregateNode

                if (aggregateAllowed)
                {
                    if (((AggregateDefinition)myComplexValue).ChainPartAggregateDefinition.Parameters.Count != 1)
                    {
                        throw new GQLAggregateArgumentException("An aggregate must have exactly one expression.");
                    }

                    if (!(((AggregateDefinition)myComplexValue).ChainPartAggregateDefinition.Parameters[0] is IDChainDefinition))
                    {
                        throw new GQLAggregateArgumentException("An aggregate must have exactly one IDNode.");
                    }

                    #region Data

                    complexIDNode = (((AggregateDefinition)myComplexValue).ChainPartAggregateDefinition.Parameters[0] as IDChainDefinition);

                    if (complexIDNode == null)
                    {
                        throw new InvalidIDNodeException("Only single IDNodes are currently allowed in aggregates!");
                    }

                    #endregion

                    #region values

                    simpleValue        = mySimpleValue;
                    extraordinaryValue = myComplexValue;

                    #endregion
                }
                else
                {
                    throw new AggregateNotAllowedException(((AggregateDefinition)myComplexValue).ChainPartAggregateDefinition.Aggregate.PluginShortName);
                }
                #endregion
            }
            else
            {
                throw new NotImplementedQLException("");
            }

            #endregion

            return(new DataContainer(new Tuple <IDChainDefinition, IDChainDefinition>(complexIDNode, null),
                                     new Tuple <AExpressionDefinition, AExpressionDefinition>(simpleValue, complexValue),
                                     new Tuple <AExpressionDefinition, AExpressionDefinition>(extraordinaryValue, null)));
        }
Ejemplo n.º 56
0
 public abstract IQueryResult Execute(IGraphDB myGraphDB,
                                      IGraphQL myGraphQL,
                                      GQLPluginManager myPluginManager,
                                      String myQuery,
                                      SecurityToken mySecurityToken,
                                      Int64 myTransactionToken);
Ejemplo n.º 57
0
        private static void CleanLowerLevel(LevelKey myLevelKey, IExpressionGraph myGraph, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            if (myLevelKey.Level > 0)
            {
                var previousLevelKey = myLevelKey.GetPredecessorLevel(myGraphDB, mySecurityToken, myTransactionToken);
                HashSet <VertexInformation> toBeDeletedNodes = new HashSet <VertexInformation>();

                foreach (var aLowerDBO in myGraph.Select(previousLevelKey, null, false))
                {
                    if (aLowerDBO.HasOutgoingEdge(myLevelKey.LastEdge.AttributeID))
                    {
                        foreach (var aVertex in aLowerDBO.GetOutgoingEdge(myLevelKey.LastEdge.AttributeID).GetTargetVertices())
                        {
                            //took the vertextype id of the levelkey, because it is possible that the vertextypeid of the vertex is something inheritated
                            VertexInformation node = new VertexInformation(aVertex.VertexTypeID, aVertex.VertexID);

                            if (!myGraph.GetLevel(myLevelKey.Level).ExpressionLevels[myLevelKey].Nodes.ContainsKey(node))
                            {
                                //a reference occurred that is not in the higher level --> found a Zoidberg

                                toBeDeletedNodes.Add(node);
                                break;
                            }
                        }
                    }
                }

                foreach (var aToBeDeletedNode in toBeDeletedNodes)
                {
                    myGraph.GetLevel(previousLevelKey.Level).RemoveNode(previousLevelKey, aToBeDeletedNode);
                }
            }
        }
Ejemplo n.º 58
0
        public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition,
                                               Object myCallingObject,
                                               IVertex myStartVertex,
                                               IGraphDB myGraphDB,
                                               SecurityToken mySecurityToken,
                                               Int64 myTransactionToken,
                                               params FuncParameter[] myParams)
        {
            #region initialization
            if (myStartVertex == null)
            {
                throw new InvalidFunctionParameterException("StartVertex", "Vertex that represents the start vertex", "null");
            }



            //set the start node
            var currentVertex = myStartVertex;

            if ((myParams[0].Value as IEnumerable <IVertex>).First() == null)
            {
                throw new InvalidFunctionParameterException("EndVertex", "Set of vertices that represents the target vertices", "null");
            }

            //set the target node
            var endVertex = (myParams[0].Value as IEnumerable <IVertex>).First();


            //set the maximum depth



            if (myAttributeDefinition == null)
            {
                throw new InvalidFunctionParameterException("EdgeType ", "Edge type not found", "faild");
            }

            UInt64 maxDepth = Convert.ToUInt64(myParams[1].Value);

            if (maxDepth < 1)
            {
                throw new InvalidFunctionParameterException("MaxDepth", "Max depth to low", maxDepth.ToString());
            }

            var myType = myGraphDB.GetVertexType <IVertexType>(
                mySecurityToken,
                myTransactionToken,
                new sones.GraphDB.Request.RequestGetVertexType(myAttributeDefinition.RelatedType.Name),
                (statistics, type) => type);

            var myEdgeType = myAttributeDefinition.ID;


            var hasProperty = myType.GetOutgoingEdgeDefinition(myAttributeDefinition.Name).InnerEdgeType.HasProperty("Weight");


            long myPropertyID = 0;

            if (hasProperty == true)
            {
                myPropertyID = myType.GetOutgoingEdgeDefinition(myAttributeDefinition.Name).InnerEdgeType.GetPropertyDefinition("Weight").ID;
            }

            Dictionary <IOutgoingEdgeDefinition, Tuple <bool, long> > edgeTypeID = new Dictionary <IOutgoingEdgeDefinition, Tuple <bool, long> >();

            var edgeType = myParams[2].Value.ToString();


            if (edgeType == "")
            {
                edgeTypeID.Add(myType.GetOutgoingEdgeDefinition(myAttributeDefinition.Name), Tuple.Create(hasProperty, myPropertyID));
            }
            else
            {
                if (edgeType.Contains("all edgeType"))
                {
                    edgeTypeID = this.AllEdgeWithTargetVertex(myType);
                }
                else
                {
                    edgeTypeID = this.StringParser(edgeType, myType);
                    if (!edgeTypeID.ContainsKey(myType.GetOutgoingEdgeDefinition(myAttributeDefinition.Name)))
                    {
                        edgeTypeID.Add(myType.GetOutgoingEdgeDefinition(myAttributeDefinition.Name), Tuple.Create(hasProperty, myPropertyID));
                    }
                }
            }



            List <UInt64> depthBuffer = new List <UInt64>();

            List <Tuple <ISingleEdge, IOutgoingEdgeDefinition> > edgeBuffer = new List <Tuple <ISingleEdge, IOutgoingEdgeDefinition> >();

            List <double>  distanceBuffer = new List <double>();
            List <IVertex> VertexBuffer   = new List <IVertex>();



            BufferDijkstra buf   = new BufferDijkstra();
            DataDijkstra   lists = new DataDijkstra();



            buf.Add(myStartVertex, 0, 0);
            lists.Add(currentVertex, 0, 0, null, null, currentVertex);



            bool endVertexFlag = false;

            #endregion
            #region Dijkstra algorithm



            double currentVertexDistance = 0;
            ulong  currentVertexDepth    = 0;

            double endVertexDistance = 0;
            ulong  endvertexDepth    = 0;

            Stopwatch clock = new Stopwatch();
            clock.Start();

            while (buf.Count != 0)
            {
                if (currentVertexDepth < maxDepth)
                {
                    List <Tuple <ISingleEdge, IOutgoingEdgeDefinition> > AllsingleEdge = new List <Tuple <ISingleEdge, IOutgoingEdgeDefinition> >();
                    foreach (IOutgoingEdgeDefinition id in edgeTypeID.Keys)
                    {
                        var hyperEdge = currentVertex.GetOutgoingHyperEdge(id.ID);

                        if (hyperEdge != null)
                        {
                            var singleEdge = hyperEdge.GetAllEdges();
                            foreach (ISingleEdge value in singleEdge)
                            {
                                AllsingleEdge.Add(Tuple.Create(value, id));
                            }
                        }
                    }



                    if (AllsingleEdge != null)
                    {
                        for (int iCount = 0; iCount < AllsingleEdge.Count(); iCount++)
                        {
                            var elementSingleEdge = AllsingleEdge.ElementAt(iCount);
                            var TargetVertex      = elementSingleEdge.Item1.GetTargetVertex();



                            double current_distance = 0;

                            if (edgeTypeID[elementSingleEdge.Item2].Item1 == true)
                            {
                                current_distance = Math.Abs(AllsingleEdge.ElementAt(iCount).Item1.GetProperty <double>(edgeTypeID[elementSingleEdge.Item2].Item2));
                            }
                            else
                            {
                                current_distance = 1;
                            }


                            var current_singleEdge = AllsingleEdge.ElementAt(iCount).Item1;

                            var TargetVertexID = lists.GetElement(TargetVertex.VertexID);

                            if (TargetVertexID == null)
                            {
                                if (!endVertexFlag)
                                {
                                    buf.Add(TargetVertex,
                                            current_distance + currentVertexDistance,
                                            currentVertexDepth + 1);



                                    lists.Add(TargetVertex,
                                              current_distance + currentVertexDistance,
                                              currentVertexDepth + 1,
                                              current_singleEdge,
                                              elementSingleEdge.Item2,
                                              currentVertex);
                                }
                                else
                                if (endVertexDistance > currentVertexDistance + current_distance ||
                                    (endVertexDistance == currentVertexDistance + current_distance &&
                                     endvertexDepth > currentVertexDepth + 1))
                                {
                                    buf.Add(TargetVertex,
                                            current_distance + currentVertexDistance,
                                            currentVertexDepth + 1);


                                    lists.Add(TargetVertex,
                                              current_distance + currentVertexDistance,
                                              currentVertexDepth + 1,
                                              current_singleEdge,
                                              elementSingleEdge.Item2,
                                              currentVertex);
                                }
                            }

                            else
                            {
                                if (currentVertexDistance + current_distance < TargetVertexID.Item2)
                                {
                                    if (!endVertexFlag)
                                    {
                                        buf.Set(TargetVertexID.Item2, TargetVertex,
                                                current_distance + currentVertexDistance,
                                                currentVertexDepth + 1);

                                        lists.Set(TargetVertex,
                                                  current_distance + currentVertexDistance,
                                                  currentVertexDepth + 1,
                                                  current_singleEdge,
                                                  elementSingleEdge.Item2,
                                                  currentVertex);
                                    }

                                    else
                                    if (endVertexDistance > currentVertexDistance + current_distance ||
                                        (endVertexDistance == currentVertexDistance + current_distance &&
                                         endvertexDepth > currentVertexDepth + 1))
                                    {
                                        buf.Set(TargetVertexID.Item2, TargetVertex,
                                                current_distance + currentVertexDistance,
                                                currentVertexDepth + 1);

                                        lists.Set(TargetVertex,
                                                  current_distance + currentVertexDistance,
                                                  currentVertexDepth + 1,
                                                  current_singleEdge,
                                                  elementSingleEdge.Item2,
                                                  currentVertex);
                                    }
                                }
                                else if (currentVertexDistance + current_distance == TargetVertexID.Item2 && currentVertexDepth + 1 < TargetVertexID.Item3)
                                {
                                    if (!endVertexFlag)
                                    {
                                        buf.Set(TargetVertexID.Item2, TargetVertex,
                                                current_distance + currentVertexDistance,
                                                currentVertexDepth + 1);

                                        lists.Set(TargetVertex,
                                                  current_distance + currentVertexDistance,
                                                  currentVertexDepth + 1,
                                                  current_singleEdge,
                                                  elementSingleEdge.Item2,
                                                  currentVertex);
                                    }
                                    else
                                    if (endVertexDistance > currentVertexDistance + current_distance ||
                                        (endVertexDistance == currentVertexDistance + current_distance &&
                                         endvertexDepth > currentVertexDepth + 1))
                                    {
                                        buf.Set(TargetVertexID.Item2, TargetVertex,
                                                current_distance + currentVertexDistance,
                                                currentVertexDepth + 1);

                                        lists.Set(TargetVertex,
                                                  current_distance + currentVertexDistance,
                                                  currentVertexDepth + 1,
                                                  current_singleEdge,
                                                  elementSingleEdge.Item2,
                                                  currentVertex);
                                    }
                                }
                            }


                            if (TargetVertex == endVertex)
                            {
                                endVertexFlag = true;
                                var endNode = lists.GetElement(endVertex.VertexID);
                                endVertexDistance = endNode.Item2;
                                endvertexDepth    = endNode.Item3;
                            }
                        }
                    }
                }
                //delate from Buffer current Vertex or all
                if (currentVertex == endVertex)
                {
                    buf.Clear();
                }
                else
                {
                    buf.Remove(currentVertexDistance, currentVertex.VertexID);
                }

                //Minimum distance from Buffer
                if (buf.Count != 0)
                {
                    var minVertex = buf.Min();
                    currentVertex         = minVertex.Item1;
                    currentVertexDistance = minVertex.Item2;
                    currentVertexDepth    = minVertex.Item3;
                }
            }
            #endregion

            clock.Stop();


            #region create output

            edgeBuffer.Add(null);
            currentVertex = endVertex;
            while (currentVertex != myStartVertex)
            {
                var current_tuple = lists.GetElement(currentVertex.VertexID);

                if (current_tuple == null)
                {
                    throw new InvalidFunctionParameterException("MaxDepth", "Max depth to low or end node is not with start node connected, find't end node", maxDepth);
                }

                VertexBuffer.Add(currentVertex);


                distanceBuffer.Add(current_tuple.Item2);
                depthBuffer.Add(current_tuple.Item3);
                edgeBuffer.Add(current_tuple.Item4);
                currentVertex = current_tuple.Item5;
            }
            depthBuffer.Add(0);
            distanceBuffer.Add(0);
            VertexBuffer.Add(myStartVertex);

            edgeBuffer.Add(null);



            var path = CreateVertexView(myPropertyID, VertexBuffer, distanceBuffer, edgeBuffer, depthBuffer);

            #endregion

            distanceBuffer = null;
            VertexBuffer   = null;
            edgeBuffer     = null;
            depthBuffer    = null;
            buf.Clear();
            lists.Clear();
            buf   = null;
            lists = null;


            return(new FuncParameter(path));
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Algorithm Dijkstra for find all shortest path from start Vertex to all others Vertices
        /// </summary>
        /// <param name="myAttributeDefinition"></param>
        /// <param name="myCallingObject"></param>
        /// <param name="myStartVertex"></param>
        /// <param name="myGraphDB"></param>
        /// <param name="maxDepth"></param>
        /// <param name="mySecurityToken"></param>
        /// <param name="myTransactionToken"></param>
        /// <returns></returns>
        private Tuple <IVertex, DataDijkstra> FindShortPathToAll(IAttributeDefinition myAttributeDefinition,
                                                                 Object myCallingObject,
                                                                 IVertex myStartVertex,
                                                                 IGraphDB myGraphDB,
                                                                 UInt64 maxDepth,
                                                                 SecurityToken mySecurityToken,
                                                                 Int64 myTransactionToken)
        {
            if (myStartVertex == null)
            {
                throw new InvalidFunctionParameterException("StartVertex", "Vertex that represents the start vertex", "null");
            }

            //set the start node
            var currentVertex = myStartVertex;

            var myType = myGraphDB.GetVertexType <IVertexType>(mySecurityToken,
                                                               myTransactionToken,
                                                               new sones.GraphDB.Request.RequestGetVertexType(myAttributeDefinition.RelatedType.Name),
                                                               (statistics, type) => type);

            var myEdgeType = myAttributeDefinition.ID;


            var hasProperty = myType.GetOutgoingEdgeDefinition(myAttributeDefinition.Name).InnerEdgeType.HasProperty("Weight");


            long myPropertyID = 0;

            if (hasProperty == true)
            {
                myPropertyID = myType.GetOutgoingEdgeDefinition(myAttributeDefinition.Name).InnerEdgeType.GetPropertyDefinition("Weight").ID;
            }

            var edgeTypeDifinition = myType.GetOutgoingEdgeDefinition(myAttributeDefinition.Name);

            DataDijkstra   lists  = new DataDijkstra();
            BufferDijkstra buffer = new BufferDijkstra();


            buffer.Add(myStartVertex, 0, 0);
            lists.Add(currentVertex, 0, 0, null, null, currentVertex);


            double currentVertexDistance = 0;
            ulong  currentVertexDepth    = 0;


            while (buffer.Count != 0)
            {
                if (currentVertexDepth < maxDepth)
                {
                    var hyperEdge = currentVertex.GetOutgoingHyperEdge(myEdgeType);

                    if (hyperEdge != null)
                    {
                        var singleEdge = hyperEdge.GetAllEdges();


                        for (int iCount = 0; iCount < singleEdge.Count(); iCount++)
                        {
                            var TargetVertex = singleEdge.ElementAt(iCount).GetTargetVertex();


                            double current_distance;

                            if (hasProperty == true)
                            {
                                current_distance = Math.Abs(singleEdge.ElementAt(iCount).GetProperty <double>(myPropertyID));
                            }
                            else
                            {
                                current_distance = 1;
                            }

                            var current_singleEdge = singleEdge.ElementAt(iCount);

                            var TargetVertexID = lists.GetElement(TargetVertex.VertexID);

                            if (TargetVertexID == null)
                            {
                                buffer.Add(TargetVertex,
                                           current_distance + currentVertexDistance,
                                           currentVertexDepth + 1);



                                lists.Add(TargetVertex,
                                          current_distance + currentVertexDistance,
                                          currentVertexDepth + 1,
                                          current_singleEdge,
                                          edgeTypeDifinition,
                                          currentVertex);
                            }
                            else
                            {
                                if (currentVertexDistance + current_distance < TargetVertexID.Item2)
                                {
                                    buffer.Set(TargetVertexID.Item2, TargetVertex,
                                               current_distance + currentVertexDistance,
                                               currentVertexDepth + 1);

                                    lists.Set(TargetVertex,
                                              current_distance + currentVertexDistance,
                                              currentVertexDepth + 1,
                                              current_singleEdge,
                                              edgeTypeDifinition,
                                              currentVertex);
                                }
                                else
                                if (currentVertexDistance + current_distance == TargetVertexID.Item2 && currentVertexDepth + 1 < TargetVertexID.Item3)
                                {
                                    buffer.Set(TargetVertexID.Item2, TargetVertex,
                                               current_distance + currentVertexDistance,
                                               currentVertexDepth + 1);

                                    lists.Set(TargetVertex,
                                              current_distance + currentVertexDistance,
                                              currentVertexDepth + 1,
                                              current_singleEdge,
                                              edgeTypeDifinition,
                                              currentVertex);
                                }
                            }
                        }
                        //delate from Buffer Vertex and any information
                    }
                }

                buffer.Remove(currentVertexDistance, currentVertex.VertexID);



                //Minimum in distance from Buffer
                if (buffer.Count != 0)
                {
                    var minVertex = buffer.Min();
                    currentVertex         = minVertex.Item1;
                    currentVertexDistance = minVertex.Item2;
                    currentVertexDepth    = minVertex.Item3;
                }
            }
            var result = Tuple.Create(myStartVertex, lists);

            buffer.Clear();
            lists.Clear();
            buffer = null;
            lists  = null;

            return(result);
        }
Ejemplo n.º 60
0
 public override FuncParameter ExecFunc(IAttributeDefinition myAttributeDefinition, Object myCallingObject, IVertex myDBObject, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken, params FuncParameter[] myParams)
 {
     if (myCallingObject != null)
     {
         return(new FuncParameter(true));
     }
     else
     {
         return(new FuncParameter(false));
     }
 }