public void Allow_Publish_For_Impersonated_Repository() { // construct the model // construct the model AuthToken authToken = new AuthToken() { UserId = 1, RespositoryId = 2 }; File fakeFile = new File() { Name = "test1", FileId = 100, RepositoryId = 1, CreatedBy = 1, Status = FileStatus.None.ToString() }; PublishMessage model = new PublishMessage() { RepositoryId = 1, AuthToken = authToken, FileId = fakeFile.FileId, UserId = 1 }; this.repository = new Repository() { BaseRepositoryId = 2, Name = "test", IsImpersonating = true, AccessToken = "accessToken", RefreshToken = "refreshToken", TokenExpiresOn = DateTime.UtcNow.AddHours(1), BaseRepository = new BaseRepository { Name = "SkyDrive" } }; SkyDriveFileService skyDriveFileService = this.GetSkyDriveFileService(); IFileProcesser fileProcessor = new StubIFileProcesser() { DownloadDocumentFile = file => new DataDetail() { FileNameToDownLoad = "abc.xyz" } }; string fileIdentifier; using (ShimsContext.Create()) { ShimFileFactory.GetFileTypeInstanceStringIBlobDataRepositoryIFileRepositoryIRepositoryService = (fileExtension, blobDataRepository, fileDataRepository, repositoryService) => fileProcessor; fileIdentifier = skyDriveFileService.PublishFile(model); } Assert.IsFalse(string.IsNullOrEmpty(fileIdentifier)); }
/// <summary> /// Method to publish file /// </summary> /// <param name="postFileData">PublishMessage object</param> /// <returns>returns File Identifier</returns> public override string PublishFile(PublishMessage postFileData) { var file = this.GetFileByFileId(postFileData.FileId); IEnumerable<DM.FileColumnType> fileColumnTypes = null; IEnumerable<DM.FileColumnUnit> fileColumnUnits = null; OperationStatus status = null; Encoding encoding = Encoding.UTF8; string identifier = string.Empty; var repository = this.RepositoryService.GetRepositoryById(postFileData.RepositoryId); string authorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(postFileData.UserName /*UserName*/ + ":" + postFileData.Password /*Password*/)); string baseRepoName = this.RepositoryDetails.GetBaseRepositoryName(repository.BaseRepositoryId); this.RepositoryAdapter = new DataVerseAdapter(); var dataFile = this.GetDataFile(file); var repositoryModel = GetRepositoryModel(repository, authorization); PublishDataVerseFileModel publishDataVerseFileModel = new PublishDataVerseFileModel() { File = dataFile, RepositoryModel = repositoryModel, FileColumnTypes = fileColumnTypes, FileColumnUnits = fileColumnUnits, }; status = this.RepositoryAdapter.PostFile(publishDataVerseFileModel); return identifier; }
/// <summary> /// Method to publish file /// </summary> /// <param name="postFileData">PostFileModel object</param> /// <returns>returns File Identifier</returns> public override string PublishFile(PublishMessage publishModel) { string fileIndentifier = null; var file = this.GetFileByFileId(publishModel.FileId); Check.IsNotNull<DM.File>(file, "fileToPublish"); IEnumerable<DM.FileColumnType> fileColumnTypes = null; IEnumerable<DM.FileColumnUnit> fileColumnUnits = null; OperationStatus status = null; Encoding encoding = Encoding.UTF8; string identifier = string.Empty; Repository repository = this.RepositoryService.GetRepositoryById(publishModel.RepositoryId); string baseRepoName = repository.BaseRepository.Name; this.RepositoryAdapter = this.RepositoryAdapterFactory.GetRepositoryAdapter(baseRepoName); DataFile dataFile = this.GetDataFile(file); if (file.FileColumns != null && file.FileColumns.Count > 0) { // before posting the file set file column units and types fileColumnTypes = this.RetrieveFileColumnTypes(); fileColumnUnits = this.RetrieveFileColumnUnits(); } // Set the user Id on AuthToken publishModel.AuthToken.UserId = publishModel.UserId; publishModel.AuthToken.RespositoryId = repository.RepositoryId; AuthToken authToken = this.GetOrUpdateAuthTokens(repository, publishModel.AuthToken); PublishSkyDriveFileModel publishSkyDriveFileModel = new PublishSkyDriveFileModel() { File = dataFile, Repository = repository, FileColumnTypes = fileColumnTypes, FileColumnUnits = fileColumnUnits, AuthToken = authToken }; //post the file status = this.RepositoryAdapter.PostFile(publishSkyDriveFileModel); if (status.Succeeded) { fileIndentifier = (string)status.CustomReturnValues; } return fileIndentifier; }
public void Allow_ProcessMessage() { this.addedMessage = null; this.deletedMessage = null; this.fileUpdated = false; PublishMessage message = new PublishMessage() { RepositoryId = 1, FileId = 1 }; IMessageHandler publishQueueService = this.GetPublishQueueService(); using (ShimsContext.Create()) { ShimConfigReader<int>.GetRepositoryConfigValuesStringString = (baseRepositoryName, SettingName) => { return 3; }; publishQueueService.ProcessMessage(message); } Assert.IsTrue(this.deletedMessage == message); Assert.IsTrue(this.file.Status == FileStatus.Verifying.ToString()); var verifyFileMessage = this.addedMessage as VerifyFileMessage; Assert.IsNotNull(verifyFileMessage); }
public void Error_When_PublishFile_Throws_Exception_AND_Exceeds_Maximum_Retries() { this.addedMessage = null; this.deletedMessage = null; this.fileUpdated = false; int startCount = 0; PublishMessage message = new PublishMessage() { RepositoryId = 1, FileId = 1, RetryCount = startCount }; PublishQueueService publishQueueService = this.GetPublishQueueService(); this.fileService = new StubIFileService() { PublishFilePublishMessage = (publishMessage) => { throw new Exception("test"); }, GetFileByFileIdInt32 = (fileId) => { this.file = new File() { FileId = 1 }; return file; }, UpdateFileFile = (file) => { this.file = file; return true; }, }; using (ShimsContext.Create()) { ShimConfigReader<int>.GetRepositoryConfigValuesStringString = (baseRepositoryName, SettingName) => { return 3; }; publishQueueService.ProcessMessage(message); } Assert.IsTrue(this.file.Status == FileStatus.Error.ToString()); Assert.IsTrue(this.deletedMessage == message); }
/// <summary> /// Performs the necessary validations required for the file to be published /// </summary> /// <param name="message">Publish Message</param> /// <returns>Operation Status</returns> public virtual void ValidateForPublish(PublishMessage message) { Repository repository = this.RepositoryService.GetRepositoryById(message.RepositoryId); DM.File file = this.GetFileByFileId(message.FileId); if (null == file) { throw new DataFileNotFoundException() { FileId = message.FileId }; } FileStatus fileStatus = (FileStatus)Enum.Parse(typeof(FileStatus), file.Status); if (fileStatus == FileStatus.Posted || fileStatus == FileStatus.Verifying || fileStatus == FileStatus.Inqueue) { throw new FileAlreadyPublishedException() { FileStatus = file.Status, FileId = message.FileId, RepositoryId = message.RepositoryId }; } this.ValidateMetadata(message.RepositoryId, message.FileId); }
/// <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; }
public virtual string PublishFile(PublishMessage postFileData) { throw new NotSupportedException(); }
/// <summary> /// Creates an instance of VerifyFileMessage from PublishMessage and Adds the VerifyFileMessage to the Queue. /// </summary> /// <param name="publishMessage">PublishMessage instance.</param> private void AddVerifyFileMessageToQueue(PublishMessage publishMessage) { VerifyFileMessage message = new VerifyFileMessage() { FileId = publishMessage.FileId, RepositoryId = publishMessage.RepositoryId, UserId = publishMessage.UserId, ProcessOn = DateTime.UtcNow.AddSeconds(this.VerifyFileInterval), UserName = publishMessage.UserName, Password = publishMessage.Password }; this.QueueRepository.AddMessageToQueue(message); //// TODO Need to use the Async Method //// return this.queueRepository.AddMessageToQueueAsync(message); }
/// <summary> /// Performs the necessary validations required for the file to be published in skydrive /// </summary> /// <param name="message">Publish Message</param> public override void ValidateForPublish(PublishMessage message) { base.ValidateForPublish(message); Repository repository = this.RepositoryService.GetRepositoryById(message.RepositoryId); }
public HttpResponseMessage Publish(PublishMessage publishMessage) { string message = string.Empty; HttpError error = null; try { if (null == publishMessage) { diagnostics.WriteErrorTrace(TraceEventId.Exception, "publishMessage null"); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(MessageStrings.Argument_Error_Message_Template, "publishMessage")); } publishMessage.UserId = this.user.UserId; Repository repository = this.repositoryService.GetRepositoryById(publishMessage.RepositoryId); if (null == repository) { diagnostics.WriteErrorTrace(TraceEventId.Exception, "Repository is null"); return Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Invalid_Repository_id); } // Create file service instance this.fileService = this.fileServiceFactory.GetFileService(repository.BaseRepository.Name); File file = this.fileService.GetFileByFileId(publishMessage.FileId); if (null == file) { diagnostics.WriteErrorTrace(TraceEventId.Exception, "File is null"); return Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Invalid_File_Id); } // Perform validations this.fileService.ValidateForPublish(publishMessage); // Publish the message to queue this.publishQueueService.PostFileToQueue(publishMessage); file.Status = FileStatus.Inqueue.ToString(); file.RepositoryId = repository.RepositoryId; file.ModifiedOn = DateTime.UtcNow; // update the file status and associate repository this.fileService.UpdateFile(file); return Request.CreateResponse(HttpStatusCode.OK); } catch (ArgumentException argumentException) { error = new HttpError(string.Format(MessageStrings.Argument_Error_Message_Template, argumentException.ParamName)); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } catch (MetadataValidationException metadataValidationException) { if (metadataValidationException.NotFound) { error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Required_Field_Metadata_Not_Found_Template, metadataValidationException.FieldName)); } else if (metadataValidationException.MetadataTypeNotFound) { error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Metadata_Type_Not_Found_Template, metadataValidationException.FieldName)); } else { error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Metadata_Field_Value_Type_Mismatch_Template, metadataValidationException.FieldName)); } return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } catch (DataFileNotFoundException fileNotFoundException) { error = fileNotFoundException.GetHttpError(MessageStrings.FileNotFound); return Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } catch (RepositoryNotFoundException repositoryNotFoundException) { error = repositoryNotFoundException.GetHttpError(MessageStrings.Invalid_Repository_id); return Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } catch (AccessTokenNotFoundException accessTokenNotFoundException) { error = accessTokenNotFoundException.GetHttpError(MessageStrings.Access_Token_Is_Null); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } catch (FileAlreadyPublishedException fileAlreadyPublishedException) { error = fileAlreadyPublishedException.GetHttpError(MessageStrings.File_Already_Published); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } }
public HttpResponseMessage Publish(string nameIdentifier, int fileId, string repositoryName) { string message = string.Empty; HttpError error = null; try { Check.IsNotEmptyOrWhiteSpace(nameIdentifier, "nameIdentifier"); Check.IsNotEmptyOrWhiteSpace(repositoryName, "repositoryName"); User impersonatedUser = IdentityHelper.GetUser(this.userService, nameIdentifier); Repository repository = this.repositoryService.GetRepositoryByName(repositoryName); if (repository == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Repository_Not_Found); } else if (repository.IsImpersonating != true) { return Request.CreateErrorResponse(HttpStatusCode.NotImplemented, MessageStrings.ServiceCannotPostFileToARepositoryThatIsNotImpersonated); } PublishMessage publishMessage = new PublishMessage() { UserId = impersonatedUser.UserId, FileId = fileId, RepositoryId = repository.RepositoryId, AuthToken = new AuthToken() }; // Create file service instance this.fileService = this.fileServiceFactory.GetFileService(repository.BaseRepository.Name); File file = this.fileService.GetFileByFileId(publishMessage.FileId); if (null == file) { diagnostics.WriteErrorTrace(TraceEventId.Exception, "File is null"); return Request.CreateErrorResponse(HttpStatusCode.NotFound, MessageStrings.Invalid_File_Id); } // Perform validations this.fileService.ValidateForPublish(publishMessage); // Publish the message to queue this.publishQueueService.PostFileToQueue(publishMessage); file.Status = FileStatus.Inqueue.ToString(); file.RepositoryId = repository.RepositoryId; file.ModifiedOn = DateTime.UtcNow; // update the file status and associate repository this.fileService.UpdateFile(file); return Request.CreateResponse(HttpStatusCode.OK); } catch (ArgumentException argumentException) { error = new HttpError(string.Format(MessageStrings.Argument_Error_Message_Template, argumentException.ParamName)); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } catch (MetadataValidationException metadataValidationException) { if (metadataValidationException.NotFound) { error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Required_Field_Metadata_Not_Found_Template, metadataValidationException.FieldName)); } else if (metadataValidationException.MetadataTypeNotFound) { error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Metadata_Type_Not_Found_Template, metadataValidationException.FieldName)); } else { error = metadataValidationException.GetHttpError(string.Format(MessageStrings.Metadata_Field_Value_Type_Mismatch_Template, metadataValidationException.FieldName)); } return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } catch (DataFileNotFoundException fileNotFoundException) { error = fileNotFoundException.GetHttpError(MessageStrings.FileNotFound); return Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } catch (RepositoryNotFoundException repositoryNotFoundException) { error = repositoryNotFoundException.GetHttpError(MessageStrings.InvalidRepositoryName); return Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } catch (AccessTokenNotFoundException accessTokenNotFoundException) { error = accessTokenNotFoundException.GetHttpError(MessageStrings.Access_Token_Is_Null); return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, error); } catch (FileAlreadyPublishedException fileAlreadyPublishedException) { error = fileAlreadyPublishedException.GetHttpError(MessageStrings.File_Already_Published); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } }
/// <summary> /// Performs the necessary validations required for the file to be published in skydrive /// </summary> /// <param name="message">Publish Message</param> public override void ValidateForPublish(PublishMessage message) { base.ValidateForPublish(message); Repository repository = this.RepositoryService.GetRepositoryById(message.RepositoryId); if ((bool)repository.IsImpersonating) { return; } if (string.IsNullOrEmpty(message.AuthToken.AccessToken)) { AuthToken userAuthToken = this.userService.GetUserAuthToken(message.UserId, message.RepositoryId); if (null == userAuthToken) { throw new AccessTokenNotFoundException() { RepositoryId = message.RepositoryId, UserId = message.RepositoryId }; } } }
public void Return_ErrorCode_When_Adapter_Returns_Failure() { // construct the model AuthToken authToken = new AuthToken() { AccessToken = "accessToken", RefreshToken = "refreshToken", TokenExpiresOn = DateTime.UtcNow.AddHours(-1), RespositoryId = 1 }; File fakeFile = new File() { Name = "test1", FileId = 100, RepositoryId = 1, CreatedBy = 1, Status = FileStatus.None.ToString() }; PublishMessage model = new PublishMessage() { RepositoryId = 3, AuthToken = authToken, FileId = fakeFile.FileId, UserId = 1 }; this.repository = new Repository() { BaseRepositoryId = 2, Name = "test", IsImpersonating = false, BaseRepository = new BaseRepository { Name = "SkyDrive" } }; this.userAuthToken = null; var fileProvider = this.GetSkyDriveFileService(); this.skyDriveAdapter = new Microsoft.Research.DataOnboarding.RepositoryAdapters.Interfaces.Fakes.StubIRepositoryAdapter() { PostFilePublishFileModel = (publishFileModel) => { OperationStatus status = OperationStatus.CreateFailureStatus("error"); return status; }, }; IFileProcesser fileProcessor = new StubIFileProcesser() { DownloadDocumentFile = file => new DataDetail() { FileNameToDownLoad = "abc.xyz" } }; string fileIdentifier; using (ShimsContext.Create()) { ShimFileFactory.GetFileTypeInstanceStringIBlobDataRepositoryIFileRepositoryIRepositoryService = (fileExtension, blobDataRepository, fileDataRepository, repositoryService) => fileProcessor; ShimSkyDriveFileService.AllInstances.GetOrUpdateAuthTokensRepositoryAuthToken = (skyDriveFileService, repository, at) => new AuthToken(); fileIdentifier = fileProvider.PublishFile(model); } Assert.IsTrue(string.IsNullOrEmpty(fileIdentifier)); }
/// <summary> /// Updates the FileStatus as Verifying. /// </summary> /// <param name="publishMessage">PublishMessage instance.</param> /// <param name="fileIdentifier">File Identifier.</param> private void UpdateFileStatusAndDeleteFromQueue(PublishMessage publishMessage, string fileIdentifier) { DM.File file = FileService.GetFileByFileId(publishMessage.FileId); file.RepositoryId = publishMessage.RepositoryId; file.Status = FileStatus.Verifying.ToString(); file.ModifiedOn = DateTime.UtcNow; file.Identifier = fileIdentifier; this.FileService.UpdateFile(file); this.QueueRepository.DeleteFromQueue(publishMessage); }
public void Retry_When_PublishFile_Returns_Null() { this.addedMessage = null; this.deletedMessage = null; this.fileUpdated = false; int startCount = 1; PublishMessage message = new PublishMessage() { RepositoryId = 1, FileId = 1, RetryCount = startCount }; PublishQueueService publishQueueService = this.GetPublishQueueService(); this.fileService = new StubIFileService() { PublishFilePublishMessage = (publishMessage) => { return string.Empty; } }; this.fileService = new StubIFileService() { PublishFilePublishMessage = (publishMessage) => { return null; } }; using (ShimsContext.Create()) { ShimConfigReader<int>.GetRepositoryConfigValuesStringString = (baseRepositoryName, SettingName) => { return 3; }; publishQueueService.ProcessMessage(message); } Assert.IsTrue(message.RetryCount == startCount+1); Assert.IsTrue(updatedQueueContent); Assert.IsNull(this.deletedMessage); }
/// <summary> /// Method to publish file /// </summary> /// <param name="postFileData">PublishMessage object</param> /// <returns>returns File Identifier</returns> public override string PublishFile(PublishMessage postFileData) { var file = this.GetFileByFileId(postFileData.FileId); IEnumerable<DM.FileColumnType> fileColumnTypes = null; IEnumerable<DM.FileColumnUnit> fileColumnUnits = null; OperationStatus status = null; Encoding encoding = Encoding.UTF8; string identifier = string.Empty; var repository = this.RepositoryService.GetRepositoryById(postFileData.RepositoryId); // TODO: Needs to check Filling repository credintials in case of system provided repository type if (repository.BaseRepositoryId == Constants.MerritRepositoryTypeID && repository.IsImpersonating == true) { postFileData.UserName = repository.ImpersonatingUserName; postFileData.Password = repository.ImpersonatingPassword; } string authorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(postFileData.UserName /*UserName*/ + ":" + postFileData.Password /*Password*/)); string baseRepoName = this.RepositoryDetails.GetBaseRepositoryName(repository.BaseRepositoryId); this.RepositoryAdapter = new MerritAdapter(); // This is a temporary fix to initialize citation for // Merritt repository. // TBD: move this to the base class Citation citation = default(Citation); if (string.IsNullOrWhiteSpace(file.Citation)) { User user = this.userService.GetUserById(postFileData.UserId); citation = new Citation(); citation.Title = Path.GetFileNameWithoutExtension(file.Name); citation.Publisher = string.Join(",", user.LastName, user.FirstName); } else { citation = JsonConvert.DeserializeObject<Citation>(file.Citation); } identifier = this.GetIdentifier(postFileData, authorization, repository.HttpIdentifierUriTemplate, citation); if (identifier.StartsWith("true")) { identifier = identifier.Substring(identifier.IndexOf("ark:", StringComparison.Ordinal)).Trim(); var postQueryData = GetPostQueryData(identifier, file, citation, repository, postFileData); var dataFile = this.GetDataFile(file); var repositoryModel = GetRepositoryModel(repository, authorization); if (file.FileColumns != null && file.FileColumns.Count > 0) { // before posting the file set file column units and types fileColumnTypes = this.RetrieveFileColumnTypes(); fileColumnUnits = this.RetrieveFileColumnUnits(); } PublishMerritFileModel publishMerritFileModel = new PublishMerritFileModel() { File = dataFile, RepositoryModel = repositoryModel, FileColumnTypes = fileColumnTypes, FileColumnUnits = fileColumnUnits, MerritQueryData = postQueryData }; //post the file status = this.RepositoryAdapter.PostFile(publishMerritFileModel); } else { string message = identifier.Replace("false|", ""); // Todo need to throw a custom exception throw new SystemException(message); } return identifier; }
/// <summary> /// Performs the necessary validations required for the file to be published in skydrive /// </summary> /// <param name="message">Publish Message</param> public override void ValidateForPublish(PublishMessage message) { base.ValidateForPublish(message); Repository repository = this.RepositoryService.GetRepositoryById(message.RepositoryId); if (!(bool)repository.IsImpersonating) { if (string.IsNullOrEmpty(message.UserName)) { throw new ArgumentException(string.Empty, "UserName"); } if (string.IsNullOrEmpty(message.Password)) { throw new ArgumentException(string.Empty, "Password"); } } }
private BaseMessage GetMessage() { Random rnd = new Random(1); int fileId = rnd.Next(1, 1000); int repositoryId = rnd.Next(1, 1000); BaseMessage message = new PublishMessage() { FileId = fileId, RepositoryId = repositoryId, AuthToken = new AuthToken() { AccessToken = "accessToken", RefreshToken = "refreshToken", TokenExpiresOn = DateTime.UtcNow.AddHours(1) }, UserName = "******", Password = "******", ProcessOn = DateTime.Now.AddHours(1), RetryCount = 2 }; return message; }