public string GetIdentifier(MerritQueryData queryData, RepositoryModel repositoryModel)
 {
     throw new NotImplementedException();
 }
示例#2
0
        private void WriteEML(MerritQueryData request, string filePath, DM.File file, DM.Repository repositoryData, IEnumerable<DM.FileColumnType> fileColumnTypes = null, IEnumerable<DM.FileColumnUnit> fileColumnUnits = null)
        {
            //  XmlDocument metadataDocument = new XmlDocument();
            XmlDocument emlDocument = new XmlDocument();

            // metadataDocument.LoadXml(request.MetaDataDetail.MetadataMappingXML);
            emlDocument.LoadXml(request.MetadataXML);

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(emlDocument.NameTable);
            nsmgr.AddNamespace("eml", MerritConstants.EmlNamespace);

            var repositoryMetadata = repositoryData.RepositoryMetadata.FirstOrDefault();
            if (repositoryMetadata != null)
            {
                ReplaceMetadata(file, emlDocument, nsmgr, repositoryMetadata);
            }
            // Write Parameter Metadata properties.
            if (file.FileColumns != null && file.FileColumns.Count > 0)
            {
                WriteParamMetadata(request, emlDocument, file, fileColumnTypes, fileColumnUnits);
            }

            ////Added this following conditions outside the above for loop to avoid the following conditions not to repeat every time

            ////If contact element is not there, then insert the value from creator/surname
            ManageContactElement(emlDocument);

            ////If no project title element ,then add the project title element value
            ManageProjectTitleElement(emlDocument);

            ////If datatable has no entityname ,then add the entity name
            ManageEntityNameElement(emlDocument);

            ////If datatable has no attributeList, then add attributeList node
            ManageAttributeListElement(emlDocument);

            ////set the coordinate value for geographical location 
            ManageGeographicLocationCoordinates(emlDocument);

            ////check the temporal coverage conidtions
            ManageTemporalCoverage(emlDocument);

            ////Remove the empty elements and remove the parent node when the no child node items are present
            RemoveEmptyElements(emlDocument);

            emlDocument.Save(filePath);
        }
示例#3
0
        private void WriteParamMetadata(MerritQueryData request, XmlDocument emlDocument, DM.File file, IEnumerable<DM.FileColumnType> fileColumnTypes = null, IEnumerable<DM.FileColumnUnit> fileColumnUnits = null)
        {
            XmlNamespaceManager emlNamespaceMgr = new XmlNamespaceManager(emlDocument.NameTable);
            emlNamespaceMgr.AddNamespace("eml", MerritConstants.EmlNamespace);

            XmlElement emlRoot = emlDocument.DocumentElement;

            XmlNode dataTableRef = emlRoot.SelectSingleNode(MerritConstants.SheetTableXPath, emlNamespaceMgr);
            XmlNode parentDataTable = dataTableRef.ParentNode;
            StringBuilder attibuteListBuilder;
            XElement scaleNode;
            var fileColumnType = string.Empty;
            var fileColumnUnit = string.Empty;
            List<string> sheetIds = new List<string>();

            //foreach (var param in request.ParameterMetadata)
            foreach (var param in file.FileColumns)
            {
                var sheetTable = dataTableRef.Clone();
                attibuteListBuilder = new StringBuilder();
                if (!sheetIds.Contains(param.EntityName))
                {
                    sheetIds.Add(param.EntityName);
                    foreach (var attributeParam in file.FileColumns.Where(fc => fc.EntityName == param.EntityName).ToList())
                    {
                        fileColumnType = string.Empty;
                        fileColumnUnit = string.Empty;
                        if (attributeParam.FileColumnTypeId > 0 && fileColumnTypes != null)
                        {
                            scaleNode = new XElement("measurementScale");

                            fileColumnType = fileColumnTypes.Where(fc => fc.FileColumnTypeId == attributeParam.FileColumnTypeId).FirstOrDefault().Name;
                            if (attributeParam.FileColumnUnitId > 0 && fileColumnUnits != null)
                            {
                                fileColumnUnit = fileColumnUnits.Where(fc => fc.FileColumnUnitId == attributeParam.FileColumnUnitId).FirstOrDefault().Name;
                            }
                            if (!string.IsNullOrWhiteSpace(fileColumnType))
                            {
                                switch (fileColumnType.ToUpperInvariant())
                                {
                                    case "TEXT":
                                        scaleNode = new XElement("measurementScale", new XElement("nominal", new XElement("nonNumericDomain", new XElement("textDomain", new XElement("definition", System.Security.SecurityElement.Escape(attributeParam.Description))))));
                                        break;
                                    case "DATETIME":
                                        scaleNode = new XElement("measurementScale", new XElement("dateTime", new XElement("formatString", "The user has designated this column as some form of date and/or time. No standard is specified due to DataUp coding constraints.")));
                                        break;
                                    case "NUMERIC":
                                        XElement unitsElement = new XElement("unit", new XElement("standardUnit", System.Security.SecurityElement.Escape(fileColumnUnit)));
                                        if (!string.IsNullOrWhiteSpace(fileColumnUnit))
                                        {
                                            unitsElement = new XElement("unit", new XElement("customUnit", System.Security.SecurityElement.Escape(fileColumnUnit)));
                                        }
                                        scaleNode = new XElement("measurementScale", new XElement("interval", unitsElement, new XElement("numericDomain", new XElement("numberType", "real"))));
                                        break;
                                }
                            }

                            var attibuteNode = new XElement("attribute", new XElement("attributeName", System.Security.SecurityElement.Escape(attributeParam.Name)), new XElement("attributeDefinition", System.Security.SecurityElement.Escape(attributeParam.Description)), scaleNode);

                            attibuteListBuilder.AppendLine(attibuteNode.ToString().Trim());
                        }
                    }
                    sheetTable.SelectSingleNode("entityName").InnerText = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", System.Security.SecurityElement.Escape(currentFileName), System.Security.SecurityElement.Escape(param.EntityName));
                    sheetTable.SelectSingleNode("entityDescription").InnerText = System.Security.SecurityElement.Escape(param.EntityDescription);
                    sheetTable.SelectSingleNode("attributeList").InnerXml = attibuteListBuilder.ToString();

                    parentDataTable.InsertBefore(sheetTable, dataTableRef);
                }
            }

            parentDataTable.RemoveChild(dataTableRef);
        }
示例#4
0
        private string GetIdentifierRequestBody(MerritQueryData request)
        {
            StringBuilder body = new StringBuilder();

            // Update Profile.
            string mszProfile = request["Profile"].Value;

            body.AppendLine("--" + MerritConstants.Boundary);
            body.AppendLine("Content-disposition: form-data; name=\"profile\"");

            body.AppendLine();
            body.AppendLine(mszProfile);
            body.AppendLine("--" + MerritConstants.Boundary);

            // Update ERC
            string who = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["Who"].Key, request["Who"].Value);
            string what = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["What"].Key, request["What"].Value);
            string when = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["When"].Key, request["When"].Value);

            string mszErc = string.Format(CultureInfo.InvariantCulture, "{0}%0A{1}%0A{2}", who, what, when);

            body.AppendLine("Content-disposition: form-data; name=\"erc\"");

            ////body.AppendLine("Content-type: text/plain");
            body.AppendLine();
            body.AppendLine("erc: " + mszErc);
            body.AppendLine("--" + MerritConstants.Boundary + "--");

            return body.ToString();
        }
示例#5
0
        public string GetIdentifier(MerritQueryData queryData, RepositoryModel repositoryModel)
        {
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;
            Stream dataStream = null;
            StreamReader reader = null;
            string restResponse;

            string requestBody = GetIdentifierRequestBody(queryData);

            if (queryData != null && repositoryModel != null)
            {
                IgnoreBadCertificates();

                httpRequest = (HttpWebRequest)HttpWebRequest.Create(repositoryModel.RepositoryLink);
                httpRequest.ContentType = "multipart/form-data; boundary=" + MerritConstants.Boundary;
                httpRequest.Method = "POST";
                byte[] buffer = Encoding.UTF8.GetBytes(requestBody);
                httpRequest.ContentLength = buffer.Length;
                httpRequest.Headers.Add("Authorization", "Basic " + repositoryModel.Authorization);

                try
                {
                    dataStream = httpRequest.GetRequestStream();
                    dataStream.Write(buffer, 0, buffer.Length);

                    httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                }
                catch (WebException webException)
                {
                    dataStream.Dispose();
                    httpResponse = (HttpWebResponse)webException.Response;

                    if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        return "false|" + "The username or password you entered is incorrect.";
                    }
                    else if (httpResponse.StatusCode == HttpStatusCode.NotFound)
                    {
                        return "false|" + "Issue with the repository configuration, Contact administrator.";
                    }

                    return "false|" + webException.Message;
                }
            }

            if (httpResponse.StatusCode != HttpStatusCode.OK
                && httpResponse.StatusCode != HttpStatusCode.Unauthorized
                && httpResponse.StatusCode != HttpStatusCode.NotFound)
            {
                return "false|Network Exception";
            }

            dataStream = httpResponse.GetResponseStream();
            reader = new StreamReader(dataStream);

            restResponse = reader.ReadToEnd();

            reader.Close();
            httpResponse.Close();

            if (!restResponse.Contains("ark:"))
            {
                return "false|" + "Issue with the repository configuration, Contact administrator.";
            }

            // Get Identifier from the response.
            return string.Concat("true|", restResponse.Substring(restResponse.IndexOf("ark:", StringComparison.Ordinal)).Trim());
        }
示例#6
0
        private void CreateFile(MerritConstants.FileCreationType fileCreationType, string filePath, MerritQueryData request, Encoding encoding, DM.File file, DM.Repository repository, IEnumerable<DM.FileColumnType> fileColumnTypes = null, IEnumerable<DM.FileColumnUnit> fileColumnUnits = null)
        {
            StringBuilder arguments = new StringBuilder();

            switch (fileCreationType)
            {
                case MerritConstants.FileCreationType.ManiFest:
                    arguments.AppendLine("#%dataonem_0.1");
                    arguments.AppendLine("#%profile | http://uc3.cdlib.org/registry/ingest/manifest/mrt-dataone- manifest");
                    arguments.AppendLine("#%prefix | dom: | http://uc3.cdlib.org/ontology/dataonem#");
                    arguments.AppendLine("#%prefix | mrt: | http://uc3.cdlib.org/ontology/mom#");
                    arguments.AppendLine("#%fields | dom:scienceMetadataFile | dom:scienceMetadataFormat | dom:scienceDataFile | mrt:mimeType");
                    ArrayList files = ZipUtilities.GenerateFileList(Path.GetDirectoryName(filePath));
                    foreach (string fileName in files)
                    {
                        var tempName = System.IO.Path.GetFileName(fileName);
                        arguments.AppendLine(MerritConstants.MrtErcFile + " | ERC | " + tempName + " | text/plain");
                        arguments.AppendLine(MerritConstants.MrtEmlFile + " | eml://ecoinformatics.org/eml-2.1.1 | " + tempName + " | text/xml");
                    }
                    arguments.AppendLine("#%eof");
                    break;
                case MerritConstants.FileCreationType.ERC:
                    string who = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["who"].Key, request["who"].Value);
                    string what = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["what"].Key, request["what"].Value);
                    string when = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["when"].Key, request["when"].Value);
                    string where = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", request["where"].Key, request["where"].Value);

                    arguments.AppendLine("erc:");

                    arguments.AppendLine(who);
                    arguments.AppendLine(what);
                    arguments.AppendLine(when);
                    arguments.AppendLine(where);
                    break;
                case MerritConstants.FileCreationType.EML:
                    WriteEML(request, filePath, file, repository, fileColumnTypes, fileColumnUnits);
                    break;
            }

            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                if (encoding != null)
                {
                    fileStream.Write(encoding.GetBytes(arguments.ToString()), 0, encoding.GetByteCount(arguments.ToString()));
                }
            }
        }
        /// <summary>
        /// Helper method to get the identifier from merrit.
        /// </summary>
        /// <param name="postFileData"></param>
        /// <param name="authorization"></param>
        /// <returns></returns>
        protected string GetIdentifier(PublishMessage postFileData, string authorization, string identifierUrl, Citation citation)
        {
            Check.IsNotNull(postFileData, "postFileData");
            Check.IsNotNull(authorization, "authorization");
            Check.IsNotNull(identifierUrl, "identifierUrl");
            var file = this.GetFileByFileId(postFileData.FileId);

            MerritQueryData queryData = new MerritQueryData();

            queryData.KeyValuePair = new List<DKeyValuePair<string, string>>()
            {
                         new DKeyValuePair<string, string> { Key = "Profile", Value = "oneshare_ark_only" },
                         new DKeyValuePair<string, string> { Key = "Who", Value = citation.Publisher },
                         new DKeyValuePair<string, string> { Key = "What", Value = citation.Title},
                         new DKeyValuePair<string, string> { Key = "When", Value = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture) }
            }.ToArray();

            RepositoryModel repositoryModel = new RepositoryModel()
            {
                Authorization = authorization,
                RepositoryLink = identifierUrl,
                RepositoryName = MerritConstants.OneShare
            };

            return this.RepositoryAdapter.GetIdentifier(queryData, repositoryModel);
        }
        /// <summary>
        /// Helper method to get the post query data.
        /// </summary>
        /// <param name="identifier">Unique identifier.</param>
        /// <param name="fileData">File information.</param>
        /// <param name="postFileData">Post file indormation.</param>
        /// <returns></returns>
        protected MerritQueryData GetPostQueryData(string identifier, DM.File fileData, Citation citation, Repository repository, PublishMessage postFileData)
        {
            Check.IsNotNull(identifier, "identifier");

            MerritQueryData queryData = new MerritQueryData();

            // TODO: Currently hard coded, needs to be replaced with specific value
            queryData.MetadataXML = @"<eml:eml packageId=""doi:10.5072/12345?"" system=""DCXL"" xmlns:eml=""eml://ecoinformatics.org/eml2.1.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""eml://ecoinformatics.org/eml-2.1.0 eml.xsd"">    <dataset id=""doi:10.5072/12345"">        <creator>            <!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-resource.html#creator -->            <!-- multiple creators allowed -->            <individualName>                <givenName></givenName>                <surName></surName>            </individualName>            <address>                <deliveryPoint></deliveryPoint>                <city></city>                <administrativeArea></administrativeArea><postalCode></postalCode><country></country></address><phone></phone><electronicMailAddress></electronicMailAddress><organizationName></organizationName></creator><title></title><pubDate></pubDate><abstract><para></para></abstract><publisher><para></para></publisher><url></url><contact><individualName><givenName></givenName><surName></surName></individualName><address><deliveryPoint></deliveryPoint><city></city><administrativeArea></administrativeArea><postalCode></postalCode><country></country></address><phone></phone><electronicMailAddress></electronicMailAddress><organizationName></organizationName></contact><keywordSet><keyword></keyword><keywordThesaurus></keywordThesaurus></keywordSet><coverage><!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-resource.html#coverage -->  <geographicCoverage><geographicDescription></geographicDescription><boundingCoordinates><westBoundingCoordinate></westBoundingCoordinate><eastBoundingCoordinate></eastBoundingCoordinate><northBoundingCoordinate></northBoundingCoordinate><southBoundingCoordinate></southBoundingCoordinate></boundingCoordinates></geographicCoverage><temporalCoverage id=""tempcov""><rangeOfDates> <beginDate><calendarDate></calendarDate></beginDate><endDate><calendarDate></calendarDate></endDate></rangeOfDates></temporalCoverage></coverage><project><!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-dataset.html#project --><title></title><abstract><para></para></abstract><funding><para></para></funding></project>        <intellectualRights>            <para></para>        </intellectualRights>        <dataTable>            <!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-dataTable.html#dataTable -->            <!-- dataTable is equivalent to a single tab in the excel spreadsheet.         One can have multiple data tables within the document. -->            <entityName></entityName>            <entityDescription></entityDescription>            <attributeList>                <!-- http://knb.ecoinformatics.org/software/eml/eml-2.1.0/eml-dataTable.html#attributeList -->                <!-- attribute list is equivalent to the parameter table from the requirements document.         One can have many attributes in a single table. -->                <attribute>                    <attributeName>                        <!-- non-empty string --></attributeName>                    <attributeDefinition>                        <!-- non-empty string --></attributeDefinition>                </attribute>            </attributeList>        </dataTable>    </dataset>    <additionalMetadata>        <describes>tempcov</describes>        <metadata>            <description>                <!-- non-empty string describing temporal coverage -->            </description>        </metadata>    </additionalMetadata>    <additionalMetadata>        <metadata>            <formattedCitation>                <!-- non-empty string -->            </formattedCitation>        </metadata>    </additionalMetadata></eml:eml>";

            List<DKeyValuePair<string, string>> content = new List<DKeyValuePair<string, string>>();

            Check.IsNotNull<DM.Repository>(repository, "selectedRepository");

            var repositoryMetadata = repository.RepositoryMetadata.FirstOrDefault();
            if (repositoryMetadata != null)
            {
                foreach (var repositoryMetaData in repositoryMetadata.RepositoryMetadataFields)
                {
                    DKeyValuePair<string, string> metadata = new DKeyValuePair<string, string>();
                    metadata.Key = repositoryMetaData.Name;
                    var metadataField = fileData.FileMetadataFields.Where(f => f.RepositoryMetadataFieldId == repositoryMetaData.RepositoryMetadataFieldId).FirstOrDefault();

                    if (metadataField != null)
                    {
                        metadata.Value = fileData.FileMetadataFields.Where(f => f.RepositoryMetadataFieldId == repositoryMetaData.RepositoryMetadataFieldId).FirstOrDefault().MetadataValue;
                    }

                    content.Add(metadata);
                }
            }

            //set the data to filemetadata fields
            //postFileData.FileMetaDataFields = fileData.FileMetadataFields;

            content.Add(new DKeyValuePair<string, string>() { Key = "Profile", Value = ConfigReader<string>.GetSetting("Profile_Post") });
            content.Add(new DKeyValuePair<string, string>() { Key = "who", Value = citation.Publisher });
            content.Add(new DKeyValuePair<string, string>() { Key = "what", Value = citation.Title });
            content.Add(new DKeyValuePair<string, string>() { Key = "when", Value = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture) });
            content.Add(new DKeyValuePair<string, string>() { Key = "where", Value = identifier });
            content.Add(new DKeyValuePair<string, string>() { Key = "ARK", Value = identifier });

            queryData.KeyValuePair = content.ToArray();

            return queryData;
        }