Beispiel #1
0
        public void RunVocab(String[] args)
        {
            if (args.Length < 2)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: 2 Arguments are required in order to use the -vocab mode");
                return;
            }

            if (File.Exists(args[1]))
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot output the configuration vocabulary to " + args[1] + " as a file already exists at that location");
                return;
            }

            TurtleParser ttlparser = new TurtleParser();
            StreamReader reader    = new StreamReader(Assembly.GetAssembly(typeof(IGraph)).GetManifestResourceStream("VDS.RDF.Configuration.configuration.ttl"));
            Graph        g         = new Graph();

            ttlparser.Load(g, reader);

            IRdfWriter writer;

            try
            {
                writer = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeType(Path.GetExtension(args[1])));
            }
            catch (RdfWriterSelectionException)
            {
                writer = new CompressingTurtleWriter(WriterCompressionLevel.High);
            }
            writer.Save(g, args[1]);
            Console.WriteLine("rdfWebDeploy: Configuration Vocabulary output to " + args[1]);
        }
Beispiel #2
0
        /// <summary>
        /// Loads the contents of the given File using a RDF Handler providing the RDF dataset format can be determined
        /// </summary>
        /// <param name="handler">RDF Handler to use</param>
        /// <param name="filename">File to load from</param>
        /// <param name="parser">Parser to use to parse the given file</param>
        /// <remarks>
        /// <para>
        /// If the <paramref name="parser"/> parameter is set to null then the <see cref="FileLoader">FileLoader</see> attempts to select a Store Parser by examining the file extension to select the most likely MIME type for the file.  This assume that the file extension corresponds to one of the recognized file extensions for a RDF dataset format the library supports.  If this suceeds then a parser is chosen and used to parse the input file.
        /// </para>
        /// </remarks>
        public static void Load(IRdfHandler handler, String filename, IStoreReader parser)
        {
            if (handler == null)
            {
                throw new RdfParseException("Cannot read a RDF Dataset using a null RDF Handler");
            }
            if (filename == null)
            {
                throw new RdfParseException("Cannot read a RDF Dataset from a null File");
            }

            if (!File.Exists(filename))
            {
#if SILVERLIGHT
                throw new FileNotFoundException("Cannot read a RDF Dataset from the File '" + filename + "' since it doesn't exist");
#else
                throw new FileNotFoundException("Cannot read a RDF Dataset from a File that doesn't exist", filename);
#endif
            }

            if (parser == null)
            {
                try
                {
                    parser = MimeTypesHelper.GetStoreParser(MimeTypesHelper.GetMimeType(Path.GetExtension(filename)));
                }
                catch (RdfParserSelectionException)
                {
                    //If error then we couldn't determine MIME Type from the File Extension
                    RaiseWarning("Unable to select a parser by determining MIME Type from the File Extension");
                }
            }
            if (parser == null)
            {
                //Unable to determine format from File Extension
                //Read file in locally and use the StringParser to select a parser
                StreamReader reader = new StreamReader(filename);
                String       data   = reader.ReadToEnd();
                reader.Close();
                parser = StringParser.GetDatasetParser(data);
                RaiseWarning("Used the StringParser to guess the parser to use - it guessed " + parser.GetType().Name);
                parser.Warning += RaiseStoreWarning;
                parser.Load(handler, new TextReaderParams(new StringReader(data)));
            }
            else
            {
                parser.Warning += RaiseStoreWarning;
                parser.Load(handler, new StreamParams(filename));
            }
        }
Beispiel #3
0
        /// <summary>
        /// Internal helper method for loading the data
        /// </summary>
        /// <param name="filename">File to load from</param>
        private void Initialise(String filename)
        {
            try
            {
                IStoreReader reader = MimeTypesHelper.GetStoreParser(MimeTypesHelper.GetMimeType(Path.GetExtension(filename)));
                reader.Load(this._store, new StreamParams(filename));

                this._ready = true;
            }
            catch (RdfException rdfEx)
            {
                throw new RdfStorageException("An Error occurred while trying to read the Dataset File", rdfEx);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Gets the RDF Parser for the current document (if possible)
        /// </summary>
        /// <returns></returns>
        public IRdfReader GetParser()
        {
            IRdfReader parser = null;

            if (this._enableHighlighting)
            {
                //Use the current Highlighting to select the Parser
                if (this._editor.SyntaxHighlighting != null)
                {
                    parser = SyntaxManager.GetParser(this._editor.SyntaxHighlighting.Name);
                    if (parser == null)
                    {
                        parser = StringParser.GetParser(this._editor.Text);
                    }
                }
                else
                {
                    parser = StringParser.GetParser(this._editor.Text);
                }
            }
            else if (this._currFile != null)
            {
                //Use the Current Filename to select the Parser
                try
                {
                    parser = MimeTypesHelper.GetParser(MimeTypesHelper.GetMimeType(System.IO.Path.GetExtension(this._currFile)));
                }
                catch (RdfParserSelectionException)
                {
                    parser = StringParser.GetParser(this._editor.Text);
                }
            }
            else
            {
                //Use Heuristics to guess the parser
                parser = StringParser.GetParser(this._editor.Text);
            }
            return(parser);
        }
Beispiel #5
0
        private void btnContinue_Click(object sender, RoutedEventArgs e)
        {
            if (this.chkAlwaysCheckFileAssociations.IsChecked != null)
            {
                Properties.Settings.Default.AlwaysCheckFileAssociations = (bool)this.chkAlwaysCheckFileAssociations.IsChecked;
                Properties.Settings.Default.Save();
            }

            //Set Associations appropriately
            foreach (FileAssociationInfo info in this._associations)
            {
                //Ensure File Association exists in the registry
                if (!info.Exists)
                {
                    info.Create();
                    try
                    {
                        info.ContentType = MimeTypesHelper.GetMimeType(info.Extension);
                    }
                    catch
                    {
                        //Ignore error, just means we don't know the MIME type for the Extension
                    }
                    info.PerceivedType = PerceivedTypes.Text;
                }

                //Ensure there is always a Perceived Type and a Content Type registered
                if (info.PerceivedType == PerceivedTypes.None)
                {
                    info.PerceivedType = PerceivedTypes.Text;
                }
                if (info.ContentType.Equals(String.Empty))
                {
                    try
                    {
                        String mimeType = MimeTypesHelper.GetMimeType(info.Extension);
                        info.ContentType = mimeType;
                    }
                    catch
                    {
                        //Ignore error, just means we don't know the MIME type for the Extension
                    }
                }

                //Add/Remove the association
                bool addAssociation = this.IsAssociationChecked(info.Extension);
                if (addAssociation)
                {
                    info.ProgID = RegistryProgramID;
                }
                else if (this._currentAssociations.Contains(info.Extension))
                {
                    //We want to remove the association to ourselves
                    info.ProgID = info.Extension.Substring(1) + "_auto_file";
                }

                //TODO: Ensure we are in the OpenWith List
            }

            this.Close();
        }
Beispiel #6
0
        protected override TaskResult RunTaskInternal()
        {
            MimeTypeDefinition def = MimeTypesHelper.GetDefinitions(MimeTypesHelper.GetMimeType(Path.GetExtension(this._file))).FirstOrDefault(d => d.CanWriteRdfDatasets);

            if (def == null)
            {
                throw new RdfOutputException("Cannot Export the Store to the selected File since dotNetRDF was unable to select a writer to use based on the File Extension");
            }

            IStoreWriter writer = def.GetRdfDatasetWriter();

            if (writer is IMultiThreadedWriter)
            {
                ((IMultiThreadedWriter)writer).UseMultiThreadedWriting = false;
            }

            TripleStore store = new TripleStore();

            if (writer is TriXWriter)
            {
                //For TriX must load all into memory and then write out all at once
                foreach (Uri u in this.ListGraphs())
                {
                    Graph g = new Graph();
                    this._manager.LoadGraph(g, u);
                    g.BaseUri = u;
                    store.Add(g);
                    this.Information = "Loading into memory prior to export, loaded " + store.Graphs.Sum(x => x.Triples.Count) + " Triple(s) in " + store.Graphs.Count + " Graph(s) so far...";
                    if (this.HasBeenCancelled)
                    {
                        this.Information = "Export Cancelled";
                        return(new TaskResult(true));
                    }
                }
                this.Information = "Exporting Data all at once, have " + store.Graphs.Sum(x => x.Triples.Count) + " Triple(s) in " + store.Graphs.Count + " Graph(s) to export...";
                writer.Save(store, new StreamParams(this._file));
                this.Information = "Exported " + store.Graphs.Sum(x => x.Triples.Count) + " Triple(s) in " + store.Graphs.Count + " Graph(s)";
            }
            else
            {
                if (File.Exists(this._file))
                {
                    File.Delete(this._file);
                }

                //For non-TriX formats assume it is safe to append one Graph at a time to the file
                int graphCount = 0, tripleCount = 0;
                foreach (Uri u in this.ListGraphs())
                {
                    FileStream stream = new FileStream(this._file, FileMode.Append);

                    //Load Graph into memory
                    Graph g = new Graph();
                    g.BaseUri        = u;
                    this.Information = "Loading Graph " + (u != null ? u.ToString() : "Default");
                    this._manager.LoadGraph(g, u);
                    g.BaseUri = u;

                    if (this.HasBeenCancelled)
                    {
                        stream.Close();
                        this.Information = "Export Cancelled, exported " + tripleCount + " Triple(s) in " + graphCount + " Graph(s)";
                        return(new TaskResult(true));
                    }

                    graphCount++;
                    tripleCount += g.Triples.Count;

                    //Save it
                    store.Add(g);
                    writer.Save(store, new StreamParams(stream, def.Encoding));
                    store.Remove(u);

                    this.Information = "Exporting Data graph by graph, exported " + tripleCount + " Triple(s) in " + graphCount + " Graph(s) so far...";
                }
                this.Information = "Exported " + tripleCount + " Triple(s) in " + graphCount + " Graph(s)";
            }

            return(new TaskResult(true));
        }
Beispiel #7
0
        public async Task <IActionResult> Upload()
        {
            //StringValues UniqueUploadId = default(StringValues);
            //StringValues UploadType = default(StringValues);

            //Request.Headers.TryGetValue("unique-upload-id", out UniqueUploadId);
            //Request.Headers.TryGetValue("upload-type", out UploadType);
            Request.Headers.TryGetValue("X-Upload-Title", out StringValues uploadTitle);
            Request.Headers.TryGetValue("X-Date-Taken", out StringValues dateTaken);

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(BadRequest());
            }

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var formAccumulator = new KeyValueAccumulator();

            var         objectKey      = Guid.NewGuid().ToString();
            var         thumbObjectKey = $"{Guid.NewGuid()}.jpg";
            FileStorage parent         = null;

            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit);
            var reader   = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var targetFilePath = Path.GetTempFileName();
                        using (var targetStream = System.IO.File.Create(targetFilePath)) {
                            await section.Body.CopyToAsync(targetStream);

                            _logger.LogInformation($"Copied the uploaded file '{targetFilePath}'");
                        }

                        var partName         = contentDisposition.Name;
                        var strippedFileName = contentDisposition.FileName.Replace("\"", string.Empty);
                        var mimeType         = MimeTypesHelper.GetMimeType(strippedFileName);
                        var fileExtension    = $".{strippedFileName.Split('.').LastOrDefault()}";
                        var originalFileName = strippedFileName.Replace(fileExtension, string.Empty);

                        var type   = FileStorageType.Thumb;
                        var isFile = partName.Replace("\"", string.Empty) == "file";

                        if (mimeType.Contains("image") && isFile)
                        {
                            type = FileStorageType.Image;
                        }
                        else if (mimeType.Contains("video") && isFile)
                        {
                            type = FileStorageType.Video;
                        }

                        if (isFile)
                        {
                            objectKey = $"{objectKey}{fileExtension}";
                        }

                        try {
                            using (var amazonClient = new AmazonS3Helper(_amazonS3, "attorney-journal-dev")) {
                                await amazonClient.UploadFileAsync(targetFilePath, isFile?objectKey : thumbObjectKey);
                            }

                            var date = new DateTime();
                            try {
                                date = DateTime.Parse(dateTaken);
                            } catch (System.Exception) { }

                            var newFile = new FileStorage {
                                Parent          = parent,
                                AmazonObjectKey = isFile ? objectKey : thumbObjectKey,
                                CreatedAt       = DateTime.UtcNow,
                                FileExtension   = fileExtension,
                                OriginalName    = originalFileName,
                                MimeType        = mimeType,
                                Owner           = user,
                                Type            = type,
                                Title           = uploadTitle.FirstOrDefault() ?? string.Empty,
                                DateTaken       = date
                            };

                            _context.Files.Add(newFile);

                            parent = isFile ? newFile : null;
                        } catch (AmazonS3Exception s3Exception) {
                            Console.WriteLine(s3Exception.Message, s3Exception.InnerException);
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to a model
            var formValueProvider = new FormValueProvider(BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture);

            var bindingSuccessful = await TryUpdateModelAsync(new { }, string.Empty, formValueProvider);

            if (!bindingSuccessful || !ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _context.SaveChangesAsync(CancellationToken.None);

            return(Json(new { fileUrl = AmazonS3Helper.GenerateUrl(objectKey), thumbUrl = AmazonS3Helper.GenerateUrl(thumbObjectKey), result = true }));
        }
Beispiel #8
0
        private void btnImportFile_Click(object sender, EventArgs e)
        {
            if (this.txtSourceFile.Text.Equals(string.Empty))
            {
                MessageBox.Show("Please enter a File you wish to import RDF from...", "No File Specified");
            }
            else
            {
                try
                {
                    //Try and get a Graph Parser and load
                    IRdfReader parser = MimeTypesHelper.GetParser(MimeTypesHelper.GetMimeType(Path.GetExtension(this.txtSourceFile.Text)));
                    Graph      g      = new Graph();
                    FileLoader.Load(g, this.txtSourceFile.Text);
                    this.LogImportSuccess(this.txtSourceFile.Text, 1, g.Triples.Count);

                    //Add to Store
                    try
                    {
                        this._store.Add(g);
                    }
                    catch (Exception ex)
                    {
                        this.LogImportFailure(this.txtSourceFile.Text, ex);
                        MessageBox.Show("An error occurred trying to add the RDF Graph to the Dataset:\n" + ex.Message, "File Import Error");
                        return;
                    }
                }
                catch (RdfParserSelectionException)
                {
                    try
                    {
                        //Try and get a Store Parser and load
                        IStoreReader storeparser   = MimeTypesHelper.GetStoreParser(MimeTypesHelper.GetMimeType(Path.GetExtension(this.txtSourceFile.Text)));
                        int          graphsBefore  = this._store.Graphs.Count;
                        int          triplesBefore = this._store.Graphs.Sum(g => g.Triples.Count);
                        storeparser.Load(this._store, new StreamParams(this.txtSourceFile.Text));

                        this.LogImportSuccess(this.txtSourceFile.Text, this._store.Graphs.Count - graphsBefore, this._store.Graphs.Sum(g => g.Triples.Count) - triplesBefore);
                    }
                    catch (RdfParserSelectionException selEx)
                    {
                        this.LogImportFailure(this.txtSourceFile.Text, selEx);
                        MessageBox.Show("The given file does not appear to be an RDF Graph/Dataset File Format the tool understands", "File Import Error");
                        return;
                    }
                    catch (Exception ex)
                    {
                        this.LogImportFailure(this.txtSourceFile.Text, ex);
                        MessageBox.Show("An error occurred trying to read an RDF Dataset from the file:\n" + ex.Message, "File Import Error");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    this.LogImportFailure(this.txtSourceFile.Text, ex);
                    MessageBox.Show("An error occurred trying to read an RDF Graph from the file:\n" + ex.Message, "File Import Error");
                    return;
                }

                this.stsGraphs.Text  = this._store.Graphs.Count + " Graphs";
                this.stsTriples.Text = this._store.Graphs.Sum(g => g.Triples.Count) + " Triples";
                MessageBox.Show("RDF added to the Dataset OK", "File Import Done");
            }
        }
Beispiel #9
0
        private void mnuSaveConnection_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null)
            {
                if (this.ActiveMdiChild is StoreManagerForm)
                {
                    Object manager;
                    if (this.ActiveMdiChild is StoreManagerForm)
                    {
                        manager = ((StoreManagerForm)this.ActiveMdiChild).Manager;
                    }
                    else
                    {
                        return;
                    }
                    if (manager is IConfigurationSerializable)
                    {
                        this.sfdConnection.Filter = MimeTypesHelper.GetFilenameFilter(true, false, false, false, false, false);
                        if (this.sfdConnection.ShowDialog() == DialogResult.OK)
                        {
                            //Append to existing configuration file or overwrite?
                            ConfigurationSerializationContext context;
                            if (File.Exists(this.sfdConnection.FileName))
                            {
                                DialogResult result = MessageBox.Show("The selected connection file already exists - would you like to append this connection to that file?  Click Yes to append to this file, No to overwrite and Cancel to abort", "Append Connection?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                                switch (result)
                                {
                                case DialogResult.Yes:
                                    Graph g = new Graph();
                                    FileLoader.Load(g, this.sfdConnection.FileName);
                                    context = new ConfigurationSerializationContext(g);
                                    break;

                                case DialogResult.No:
                                    context = new ConfigurationSerializationContext();
                                    break;

                                default:
                                    return;
                                }
                            }
                            else
                            {
                                //Create new configuration file
                                context = new ConfigurationSerializationContext();
                            }

                            //Save the Connection
                            ((IConfigurationSerializable)manager).SerializeConfiguration(context);

                            try
                            {
                                IRdfWriter writer = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeType(Path.GetExtension(this.sfdConnection.FileName)));
                                writer.Save(context.Graph, this.sfdConnection.FileName);
                            }
                            catch (RdfWriterSelectionException)
                            {
                                CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(WriterCompressionLevel.High);
                                ttlwriter.Save(context.Graph, this.sfdConnection.FileName);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Unable to save the current connection as it does not support this feature", "Save Unavailable", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    this.mnuSaveConnection.Enabled = false;
                }
            }
            else
            {
                this.mnuSaveConnection.Enabled = false;
            }
        }
        private bool SetOptions(String[] args)
        {
            if (args.Length == 0 || args.Length == 1 && args[0].Equals("-help"))
            {
                this.ShowUsage();
                return(false);
            }

            String arg;
            int    i = 0;

            while (i < args.Length)
            {
                arg = args[i];

                if (arg.StartsWith("-uri:"))
                {
                    if (this._mode == RdfQueryMode.Remote)
                    {
                        Console.Error.WriteLine("rdfQuery: Cannot specify input URIs as well as specifying a remote endpoint to query");
                        return(false);
                    }

                    String uri = arg.Substring(5);
                    try
                    {
                        this._mode = RdfQueryMode.Local;

                        //Try and parse RDF from the given URI
                        if (!this._print)
                        {
                            Uri   u = new Uri(uri);
                            Graph g = new Graph();
                            UriLoader.Load(g, u);
                            this._store.Add(g);
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' since -print has been specified so the query will not be executed so no need to load the data");
                        }
                    }
                    catch (UriFormatException uriEx)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' since this is not a valid URI");
                        if (this._debug)
                        {
                            this.DebugErrors(uriEx);
                        }
                    }
                    catch (RdfParseException parseEx)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' due to the following error:");
                        Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message);
                        if (this._debug)
                        {
                            this.DebugErrors(parseEx);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' due to the following error:");
                        Console.Error.WriteLine("rdfQuery: Error: " + ex.Message);
                        if (this._debug)
                        {
                            this.DebugErrors(ex);
                        }
                    }
                }
                else if (arg.StartsWith("-endpoint:"))
                {
                    if (this._mode == RdfQueryMode.Local)
                    {
                        Console.Error.WriteLine("rdfQuery: Cannot specify a remote endpoint to query as well as specifying local files and/or input URIs");
                        return(false);
                    }
                    else if (this._mode == RdfQueryMode.Remote)
                    {
                        if (!(this._endpoint is FederatedSparqlRemoteEndpoint))
                        {
                            this._endpoint = new FederatedSparqlRemoteEndpoint(this._endpoint);
                        }
                    }

                    try
                    {
                        this._mode = RdfQueryMode.Remote;
                        if (this._endpoint is FederatedSparqlRemoteEndpoint)
                        {
                            ((FederatedSparqlRemoteEndpoint)this._endpoint).AddEndpoint(new SparqlRemoteEndpoint(new Uri(arg.Substring(arg.IndexOf(':') + 1))));
                        }
                        else
                        {
                            this._endpoint = new SparqlRemoteEndpoint(new Uri(arg.Substring(arg.IndexOf(':') + 1)));
                        }
                    }
                    catch (UriFormatException uriEx)
                    {
                        Console.Error.WriteLine("rdfQuery: Unable to use remote endpoint with URI '" + arg.Substring(arg.IndexOf(':') + 1) + "' since this is not a valid URI");
                        if (this._debug)
                        {
                            this.DebugErrors(uriEx);
                        }
                        return(false);
                    }
                }
                else if (arg.StartsWith("-output:") || arg.StartsWith("-out:"))
                {
                    this._output = arg.Substring(arg.IndexOf(':') + 1);
                }
                else if (arg.StartsWith("-outformat:"))
                {
                    String format = arg.Substring(arg.IndexOf(':') + 1);
                    try
                    {
                        if (format.Contains("/"))
                        {
                            //MIME Type
                            this._graphWriter   = MimeTypesHelper.GetWriter(format);
                            this._resultsWriter = MimeTypesHelper.GetSparqlWriter(format);
                        }
                        else
                        {
                            //File Extension
                            this._graphWriter   = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeType(format));
                            this._resultsWriter = MimeTypesHelper.GetSparqlWriter(MimeTypesHelper.GetMimeType(format));
                        }
                    }
                    catch (RdfException)
                    {
                        Console.Error.WriteLine("rdfQuery: The file extension '" + format + "' could not be used to determine a MIME Type and select a writer - default writers will be used");
                    }
                }
                else if (arg.StartsWith("-syntax"))
                {
                    if (arg.Contains(':'))
                    {
                        String syntax = arg.Substring(arg.IndexOf(':') + 1);
                        switch (syntax)
                        {
                        case "1":
                        case "1.0":
                            this._parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_0;
                            break;

                        case "1.1":
                            this._parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_1;
                            break;

                        case "E":
                        case "e":
                            this._parser.SyntaxMode = SparqlQuerySyntax.Extended;
                            break;

                        default:
                            Console.Error.WriteLine("rdfQuery: The value '" + syntax + "' is not a valid query syntax specifier - assuming SPARQL 1.1 with Extensions");
                            this._parser.SyntaxMode = SparqlQuerySyntax.Extended;
                            break;
                        }
                    }
                    else
                    {
                        this._parser.SyntaxMode = SparqlQuerySyntax.Extended;
                    }
                }
                else if (arg.StartsWith("-timeout:"))
                {
                    long timeout;
                    if (Int64.TryParse(arg.Substring(arg.IndexOf(':') + 1), out timeout))
                    {
                        this._timeout = timeout;
                    }
                    else
                    {
                        Console.Error.WriteLine("rdfQuery: The value '" + arg.Substring(arg.IndexOf(':') + 1) + "' is not a valid timeout in milliseconds - default timeouts will be used");
                    }
                }
                else if (arg.StartsWith("-r:"))
                {
                    arg = arg.Substring(arg.IndexOf(':') + 1);
                    switch (arg)
                    {
                    case "rdfs":
                        ((IInferencingTripleStore)this._store).AddInferenceEngine(new RdfsReasoner());
                        break;

                    case "skos":
                        ((IInferencingTripleStore)this._store).AddInferenceEngine(new SkosReasoner());
                        break;

                    default:
                        Console.Error.WriteLine("rdfQuery: The value '" + arg + "' is not a valid Reasoner - ignoring this option");
                        break;
                    }
                }
                else if (arg.StartsWith("-partialResults"))
                {
                    if (arg.Contains(':'))
                    {
                        bool partial;
                        if (Boolean.TryParse(arg.Substring(arg.IndexOf(':') + 1), out partial))
                        {
                            this._partialResults = partial;
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfQuery: The value '" + arg.Substring(arg.IndexOf(':') + 1) + "' is not a valid boolean - partial results mode is disabled");
                        }
                    }
                    else
                    {
                        this._partialResults = true;
                    }
                }
                else if (arg.StartsWith("-noopt"))
                {
                    if (arg.Equals("-noopt"))
                    {
                        Options.QueryOptimisation   = false;
                        Options.AlgebraOptimisation = false;
                    }
                    else if (arg.Length >= 7)
                    {
                        String opts = arg.Substring(7);
                        foreach (char c in opts.ToCharArray())
                        {
                            if (c == 'a' || c == 'A')
                            {
                                Options.AlgebraOptimisation = false;
                            }
                            else if (c == 'q' || c == 'Q')
                            {
                                Options.QueryOptimisation = false;
                            }
                            else
                            {
                                Console.Error.WriteLine("rdfQuery: The value '" + c + "' as part of the -noopt argument is not supported - it has been ignored");
                            }
                        }
                    }
                }
                else if (arg.Equals("-nocache"))
                {
                    Options.UriLoaderCaching = false;
                }
                else if (arg.Equals("-nobom"))
                {
                    Options.UseBomForUtf8 = false;
                }
                else if (arg.Equals("-print"))
                {
                    this._print = true;
                }
                else if (arg.Equals("-debug"))
                {
                    this._debug = true;
                }
                else if (arg.StartsWith("-explain"))
                {
                    this._explain = true;
                    if (arg.Length > 9)
                    {
                        try
                        {
                            this._level = (ExplanationLevel)Enum.Parse(typeof(ExplanationLevel), arg.Substring(9));
                            this._level = (this._level | ExplanationLevel.OutputToConsoleStdErr | ExplanationLevel.Simulate) ^ ExplanationLevel.OutputToConsoleStdOut;
                        }
                        catch
                        {
                            Console.Error.WriteLine("rdfQuery: The argument '" + arg + "' does not specify a valid Explanation Level");
                            return(false);
                        }
                    }
                }
                else if (arg.Equals("-help"))
                {
                    //Ignore Help Argument if other arguments present
                }
                else if (arg.StartsWith("-"))
                {
                    //Report Invalid Argument
                    Console.Error.WriteLine("rdfQuery: The argument '" + arg + "' is not a supported argument - it has been ignored");
                }
                else if (i == args.Length - 1)
                {
                    //Last Argument must be the Query
                    this._query = arg;
                }
                else
                {
                    //Treat as an input file

                    if (this._mode == RdfQueryMode.Remote)
                    {
                        Console.Error.WriteLine("rdfQuery: Cannot specify local files as well as specifying a remote endpoint to query");
                        return(false);
                    }

                    try
                    {
                        this._mode = RdfQueryMode.Local;

                        //Try and parse RDF from the given file
                        if (!this._print)
                        {
                            Graph g = new Graph();
                            FileLoader.Load(g, arg);
                            this._store.Add(g);
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' since -print has been specified so the query will not be executed so no need to load the data");
                        }
                    }
                    catch (RdfParseException parseEx)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' due to the following error:");
                        Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message);
                        if (this._debug)
                        {
                            this.DebugErrors(parseEx);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' due to the following error:");
                        Console.Error.WriteLine("rdfQuery: Error: " + ex.Message);
                        if (this._debug)
                        {
                            this.DebugErrors(ex);
                        }
                    }
                }


                i++;
            }

            return(true);
        }
Beispiel #11
0
        private bool SetOptions(String[] args)
        {
            if (args.Length == 0 || (args.Length == 1 && args[0].Equals("-help")))
            {
                this.ShowUsage();
                return(false);
            }

            //Look through the arguments to see what we've been asked to do
            foreach (String arg in args)
            {
                if (arg.StartsWith("-uri:"))
                {
                    this._inputs.Add(arg);
                }
                else if (arg.StartsWith("-hs"))
                {
                    if (arg.Contains(':'))
                    {
                        bool hs;
                        if (Boolean.TryParse(arg.Substring(arg.IndexOf(':') + 1), out hs))
                        {
                            this._options.Add(new HighSpeedOption(hs));
                        }
                        else
                        {
                            this._options.Add(new HighSpeedOption(true));
                        }
                    }
                    else
                    {
                        this._options.Add(new HighSpeedOption(true));
                    }
                }
                else if (arg.StartsWith("-pp"))
                {
                    if (arg.Contains(':'))
                    {
                        bool pp;
                        if (Boolean.TryParse(arg.Substring(arg.IndexOf(':') + 1), out pp))
                        {
                            this._options.Add(new PrettyPrintingOption(pp));
                        }
                        else
                        {
                            this._options.Add(new PrettyPrintingOption(true));
                        }
                    }
                    else
                    {
                        this._options.Add(new PrettyPrintingOption(true));
                    }
                }
                else if (arg.StartsWith("-c"))
                {
                    if (arg.Contains(':'))
                    {
                        int c;
                        if (Int32.TryParse(arg.Substring(arg.IndexOf(':') + 1), out c))
                        {
                            this._options.Add(new CompressionLevelOption(c));
                        }
                        else
                        {
                            this._options.Add(new CompressionLevelOption(WriterCompressionLevel.Default));
                        }
                    }
                    else
                    {
                        this._options.Add(new CompressionLevelOption(WriterCompressionLevel.Default));
                    }
                }
                else if (arg.StartsWith("-stylesheet:"))
                {
                    String stylesheet = arg.Substring(arg.IndexOf(':') + 1);
                    this._options.Add(new StylesheetOption(stylesheet));
                }
                else if (arg.Equals("-merge"))
                {
                    this._merge = true;
                }
                else if (arg.Equals("-overwrite"))
                {
                    this._overwrite = true;
                }
                else if (arg.Equals("-dataset"))
                {
                    this._dataset = true;
                    this._merge   = true;
                }
                else if (arg.StartsWith("-out:") || arg.StartsWith("-output:"))
                {
                    this._output = arg.Substring(arg.IndexOf(':') + 1);
                    //If the Writers have not been set then we'll set them now
                    if (this._writer == null && this._storeWriter == null)
                    {
                        String format;
                        try
                        {
                            format = MimeTypesHelper.GetMimeType(Path.GetExtension(this._output));
                        }
                        catch (RdfException)
                        {
                            Console.Error.WriteLine("rdfConvert: The File Extension '" + Path.GetExtension(this._output) + "' is not permissible since dotNetRDF cannot infer a MIME type from the extension");
                            return(false);
                        }
                        try
                        {
                            this._writer = MimeTypesHelper.GetWriter(format);
                        }
                        catch (RdfException)
                        {
                            //Supress this error
                        }
                        try
                        {
                            this._storeWriter = MimeTypesHelper.GetStoreWriter(format);
                            if (this._writer == null)
                            {
                                this._merge = true;
                            }
                            else if (this._writer is NTriplesWriter && !Path.GetExtension(this._output).Equals(".nt"))
                            {
                                this._writer = null;
                                this._merge  = true;
                            }
                        }
                        catch (RdfException)
                        {
                            //Suppress this error
                        }
                        if (this._writer == null && this._storeWriter == null)
                        {
                            Console.Error.WriteLine("rdfConvert: The MIME Type '" + format + "' is not permissible since dotNetRDF does not support outputting in that format");
                            return(false);
                        }
                    }
                }
                else if (arg.StartsWith("-outformat:"))
                {
                    String format = arg.Substring(arg.IndexOf(':') + 1);
                    if (!format.Contains("/"))
                    {
                        try
                        {
                            format = MimeTypesHelper.GetMimeType(format);
                        }
                        catch (RdfException)
                        {
                            Console.Error.WriteLine("rdfConvert: The File Extension '" + format + "' is not permissible since dotNetRDF cannot infer a MIME type from the extension");
                            return(false);
                        }
                    }
                    //Validate the MIME Type
                    if (!IsValidMimeType(format))
                    {
                        Console.Error.WriteLine("rdfConvert: The MIME Type '" + format + "' is not permissible since dotNetRDF does not support outputting in that format");
                        return(false);
                    }
                    try
                    {
                        this._writer = MimeTypesHelper.GetWriter(format);
                        this._outExt = MimeTypesHelper.GetFileExtension(this._writer);
                    }
                    catch (RdfException)
                    {
                        //Supress this error
                    }
                    try
                    {
                        this._storeWriter = MimeTypesHelper.GetStoreWriter(format);
                        if (this._writer == null)
                        {
                            //In the event that we can't get a valid Writer then individual graphs
                            //will be put into a Store and output as a Dataset
                            this._merge  = true;
                            this._outExt = MimeTypesHelper.GetFileExtension(this._storeWriter);
                        }
                        else if (this._writer is NTriplesWriter && (!format.Equals("nt") || !format.Equals(".nt") || !format.Equals("text/plain")))
                        {
                            this._writer = null;
                            this._merge  = true;
                            this._outExt = MimeTypesHelper.GetFileExtension(this._storeWriter);
                        }
                    }
                    catch (RdfException)
                    {
                        //Suppress this error
                    }
                    if (this._writer == null && this._storeWriter == null)
                    {
                        Console.Error.WriteLine("rdfConvert: The MIME Type '" + format + "' is not permissible since dotNetRDF does not support outputting in that format");
                        return(false);
                    }
                }
                else if (arg.StartsWith("-outext:"))
                {
                    this._outExt = arg.Substring(arg.IndexOf(':') + 1);
                    if (!this._outExt.StartsWith("."))
                    {
                        this._outExt = "." + this._outExt;
                    }
                }
                else if (arg.Equals("-debug"))
                {
                    this._debug = true;
                }
                else if (arg.Equals("-help"))
                {
                    //Ignore help argument if other arguments are present
                }
                else if (arg.Equals("-nocache"))
                {
                    Options.UriLoaderCaching = false;
                }
                else if (arg.Equals("-nobom"))
                {
                    Options.UseBomForUtf8 = false;
                }
                else if (arg.Equals("-warnings"))
                {
                    this._warnings           = true;
                    UriLoader.Warning       += this.ShowWarning;
                    UriLoader.StoreWarning  += this.ShowWarning;
                    FileLoader.Warning      += this.ShowWarning;
                    FileLoader.StoreWarning += this.ShowWarning;
                }
                else
                {
                    //Anything else is treated as an input file
                    this._inputs.Add(arg);
                }
            }

            //If there are no this._inputs then we'll abort
            if (this._inputs.Count == 0)
            {
                Console.Error.WriteLine("rdfConvert: No Inputs were provided - please provide one/more files or URIs you wish to convert");
                return(false);
            }

            //If there are no writers specified then we'll abort
            if (this._writer == null && this._storeWriter == null)
            {
                Console.Error.WriteLine("rdfConvert: Aborting since no output options have been specified, use the -out:filename or -outformat: arguments to specify output format");
                return(false);
            }

            if (!this._outExt.Equals(String.Empty))
            {
                if (!this._outExt.StartsWith("."))
                {
                    this._outExt = "." + this._outExt;
                }
            }
            else if (!this._output.Equals(String.Empty))
            {
                this._outExt = Path.GetExtension(this._output);
            }

            //Apply the Options to the Writers
            foreach (IConversionOption option in this._options)
            {
                if (this._writer != null)
                {
                    option.Apply(this._writer);
                }
                if (this._storeWriter != null)
                {
                    option.Apply(this._storeWriter);
                }
            }

            return(true);
        }
        public string GetMimeType(string key)
        {
            var path = ComputePath(key);

            return(MimeTypesHelper.GetMimeType(path));
        }