ImportAPI
Provides methods for developing custom import utilities for documents, images, production sets, and Dynamic Objects.
using kCura.Relativity.DataReaderClient;
using kCura.Relativity.ImportAPI.Data;
using kCura.Relativity.ImportAPI.Enumeration;
using kCura.WinEDDS;
using kCura.WinEDDS.Exceptions;
using kCura.WinEDDS.Service;
using kCura.WinEDDS.Service.Kepler;
using kCura.WinEDDS.Service.Replacement;
using Monitoring;
using Monitoring.Sinks;
using Relativity.DataExchange;
using Relativity.DataExchange.Logger;
using Relativity.DataExchange.Logging;
using Relativity.DataExchange.Service;
using Relativity.Logging;
using Relativity.Transfer;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
namespace kCura.Relativity.ImportAPI
{
public class ImportAPI : IImportAPI
{
private ICaseManager _caseManager;
private WebApiCredential webApiCredential;
private IObjectTypeManager _objectTypeManager;
private IProductionManager _productionManager;
private IAuthenticationTokenProvider _authenticationTokenProvider = new NullAuthTokenProvider();
protected readonly IRunningContext _runningContext = new RunningContext();
private ILog _logger = RelativityLogger.Instance;
private Guid _apiInstanceId = Guid.NewGuid();
protected CookieContainer ;
protected NetworkCredential _credentials;
public ExecutionSourceEnum ExecutionSource { get; set; }
public ImportAPI(string userName, string password)
: this(userName, password, string.Empty, null)
{
}
public ImportAPI(string userName, string password, ILog logger)
: this(userName, password, string.Empty, logger)
{
}
public ImportAPI(string userName, string password, string webServiceUrl)
: this(userName, password, webServiceUrl, null)
{
}
public ImportAPI(string userName, string password, string webServiceUrl, ILog logger)
{
ExecutionSource = ExecutionSourceEnum.ImportAPI;
WebApiVsKeplerFactory.InvalidateCache();
ManagerFactory.InvalidateCache();
PerformLogin(userName, password, webServiceUrl);
SetUpSecureLogger(logger);
}
public static ImportAPI CreateByRsaBearerToken(string webServiceUrl, ILog logger = null)
{
return CreateByTokenProvider(webServiceUrl, new RsaBearerTokenAuthenticationProvider(), logger);
}
public static ImportAPI CreateByBearerToken(string webServiceUrl, string bearerToken, ILog logger = null)
{
return new ImportAPI("XxX_BearerTokenCredentials_XxX", bearerToken, webServiceUrl, logger);
}
public IEnumerable<Workspace> Workspaces()
{
return (from row in GetCaseManager().RetrieveAll().Tables[0].Rows.OfType<DataRow>()
select new Workspace {
ArtifactID = (int)row["ArtifactID"],
DocumentPath = (string)row["DefaultFileLocationName"],
DownloadHandlerURL = (string)row["DownloadHandlerApplicationPath"],
MatterArtifactID = (int)row["MatterArtifactID"],
Name = (string)row["Name"],
RootArtifactID = (int)row["RootArtifactID"],
RootFolderID = (int)row["RootFolderID"],
StatusCodeArtifactID = (int)row["StatusCodeArtifactID"],
ArtifactTypeId = 8,
ParentArtifactID = (int)row["ParentArtifactID"]
}).ToList();
}
public IEnumerable<ProductionSet> GetProductionSets(int workspaceArtifactID)
{
return from row1 in (from object row in GetProductionManager().RetrieveImportEligibleByContextArtifactID(workspaceArtifactID).Tables[0].Rows
select row as DataRow).Where(delegate(DataRow row1) {
if (row1 != null)
return (int)row1["ArtifactID"] > 0;
return false;
})
select new ProductionSet {
ArtifactID = (int)row1["ArtifactID"],
ArtifactTypeId = 17,
Name = (string)row1["Name"],
ParentArtifactID = workspaceArtifactID,
ProductionOrder = (int)row1["ProductionOrder"]
};
}
public IEnumerable<Field> GetWorkspaceFields(int workspaceArtifactID, int artifactTypeID)
{
IFieldQuery fieldQuery = ManagerFactory.CreateFieldQuery(_credentials, _cookieMonster, GetCorrelationId);
_logger.LogUserContextInformation("Call ImportAPI.GetWorkspaceFields", _credentials);
return (from DocumentField docField in fieldQuery.RetrieveAllAsDocumentFieldCollection(workspaceArtifactID, artifactTypeID)
select new Field {
ArtifactID = docField.FieldID,
ArtifactTypeId = docField.FieldTypeID,
Name = docField.FieldName,
FieldLength = docField.FieldLength,
FieldTypeID = (FieldTypeEnum)Enum.ToObject(typeof(FieldTypeEnum), docField.FieldTypeID),
AssociatedObjectTypeID = docField.AssociatedObjectTypeID,
UseUnicode = docField.UseUnicode,
FieldCategory = (FieldCategoryEnum)Enum.ToObject(typeof(FieldCategoryEnum), docField.FieldCategoryID),
Guids = docField.Guids,
EnableDataGrid = docField.EnableDataGrid
}).ToList();
}
public ImageImportBulkArtifactJob NewImageImportJob()
{
_runningContext.CallingAssembly = Assembly.GetCallingAssembly().GetName().Name;
_runningContext.ExecutionSource = (ExecutionSource)ExecutionSource;
return new ImageImportBulkArtifactJob(_credentials, webApiCredential, _cookieMonster, _runningContext, GetCorrelationId);
}
public ImageImportBulkArtifactJob NewProductionImportJob(int productionArtifactID)
{
_runningContext.CallingAssembly = Assembly.GetCallingAssembly().GetName().Name;
ImageImportBulkArtifactJob imageImportBulkArtifactJob = NewImageImportJob();
imageImportBulkArtifactJob.Settings.ForProduction = true;
imageImportBulkArtifactJob.Settings.ProductionArtifactID = productionArtifactID;
return imageImportBulkArtifactJob;
}
public ImportBulkArtifactJob NewNativeDocumentImportJob()
{
_runningContext.CallingAssembly = Assembly.GetCallingAssembly().GetName().Name;
return NewObjectImportJob(10);
}
public ImportBulkArtifactJob NewObjectImportJob(int artifactTypeId)
{
_runningContext.CallingAssembly = Assembly.GetCallingAssembly().GetName().Name;
_runningContext.ExecutionSource = (ExecutionSource)ExecutionSource;
return new ImportBulkArtifactJob(_credentials, webApiCredential, _cookieMonster, _runningContext, GetCorrelationId) {
Settings = {
ArtifactTypeId = artifactTypeId
}
};
}
public UploadTypeEnum GetFileUploadMode(int caseArtifactID)
{
CaseInfo caseInfo = GetCaseManager().Read(caseArtifactID);
return GetFileUploadMode(caseArtifactID, caseInfo.DocumentPath);
}
public IEnumerable<kCura.Relativity.ImportAPI.Data.ArtifactType> GetUploadableArtifactTypes(int caseArtifactID)
{
return (from DataRow singleRow in GetObjectTypeManager().RetrieveAllUploadable(caseArtifactID).Tables[0].Rows
select new kCura.Relativity.ImportAPI.Data.ArtifactType {
ID = (int)singleRow["DescriptorArtifactTypeID"],
Name = (string)singleRow["Name"]
}).ToList();
}
protected static ImportAPI CreateByTokenProvider(string webServiceUrl, IRelativityTokenProvider relativityTokenProvider, ILog logger = null)
{
string token = GetToken(relativityTokenProvider);
ImportAPI importAPI = CreateByBearerToken(webServiceUrl, token, logger);
importAPI.webApiCredential.TokenProvider = new AuthTokenProviderAdapter(relativityTokenProvider);
return importAPI;
}
protected string GetCorrelationId()
{
return _apiInstanceId.ToString();
}
private void SetUpSecureLogger(ILog logger)
{
ISecureLogFactory secureLogFactory = new ImportApiSecureLogFactory();
RelativityLogger.Instance = (logger ?? secureLogFactory.CreateSecureLogger());
}
private static string GetToken(IRelativityTokenProvider relativityTokenProvider)
{
string token;
try {
token = relativityTokenProvider.GetToken();
} catch (Exception innerException) {
throw new InvalidLoginException("Error when retrieving authentication token.", innerException);
}
if (string.IsNullOrEmpty(token))
throw new InvalidLoginException("The generated token should not be null or empty!");
return token;
}
private void PerformLogin(string userName, string password, string webServiceURL)
{
ImportCredentialManager.SessionCredentials credentials;
try {
ImportCredentialManager.WebServiceURL = webServiceURL;
credentials = ImportCredentialManager.GetCredentials(userName, password, _runningContext, GetCorrelationId);
} catch (CredentialsNotSupportedException) {
throw;
} catch (InvalidLoginException) {
throw;
} catch (RelativityNotSupportedException) {
throw;
} catch (Exception innerException) {
throw new InvalidLoginException("Login failed.", innerException);
}
_credentials = credentials.Credentials;
_logger.LogUserContextInformation("Initialized ImportAPI", _credentials);
webApiCredential = new WebApiCredential {
Credential = credentials.Credentials,
TokenProvider = _authenticationTokenProvider
};
_cookieMonster = credentials.CookieMonster;
if (_credentials == null)
throw new InvalidLoginException("Login failed.");
SendAuthenticationTypeMetric(credentials.Credentials, GetAuthenticationMethod(userName));
}
private TelemetryConstants.AuthenticationMethod GetAuthenticationMethod(string username)
{
if (!string.IsNullOrEmpty(username)) {
if (!(username == "XxX_BearerTokenCredentials_XxX"))
return TelemetryConstants.AuthenticationMethod.UsernamePassword;
return TelemetryConstants.AuthenticationMethod.BearerToken;
}
return TelemetryConstants.AuthenticationMethod.Windows;
}
private void SendAuthenticationTypeMetric(NetworkCredential credentials, TelemetryConstants.AuthenticationMethod authenticationMethod)
{
MetricService metricService = new MetricService(new ImportApiMetricSinkConfig(), KeplerProxyFactory.CreateKeplerProxy(credentials));
ILog instance = RelativityLogger.Instance;
MetricAuthenticationType metric = new MetricAuthenticationType {
CorrelationID = Guid.NewGuid().ToString(),
UnitOfMeasure = "login(s)",
AuthenticationMethod = authenticationMethod,
SystemType = instance.get_System(),
SubSystemType = instance.get_SubSystem(),
ImportApiVersion = _runningContext.ImportApiSdkVersion.ToString(),
RelativityVersion = _runningContext.RelativityVersion.ToString()
};
((IMetricService)metricService).Log((MetricBase)metric);
}
private string CreateRepositoryPath(int caseArtifactID, string defaultCasePath)
{
string str = "\\EDDS" + caseArtifactID.ToString() + "\\";
return defaultCasePath.TrimEnd(new char[1] {
'\\'
}) + str;
}
private ICaseManager GetCaseManager()
{
if (_caseManager == null)
_caseManager = ManagerFactory.CreateCaseManager(_credentials, _cookieMonster, GetCorrelationId);
_logger.LogUserContextInformation("Get CaseManager", _credentials);
return _caseManager;
}
private IObjectTypeManager GetObjectTypeManager()
{
if (_objectTypeManager == null)
_objectTypeManager = ManagerFactory.CreateObjectTypeManager(_credentials, _cookieMonster, GetCorrelationId);
_logger.LogUserContextInformation("Get ObjectTypeManager", _credentials);
return _objectTypeManager;
}
private IProductionManager GetProductionManager()
{
if (_productionManager == null)
_productionManager = ManagerFactory.CreateProductionManager(_credentials, _cookieMonster, GetCorrelationId);
_logger.LogUserContextInformation("Get ProductionManager", _credentials);
return _productionManager;
}
private UploadTypeEnum GetFileUploadMode(int caseArtifactID, string defaultCasePath)
{
string text = CreateRepositoryPath(caseArtifactID, defaultCasePath);
try {
string str = Guid.NewGuid().ToString().Replace("-", string.Empty)
.Substring(0, 5);
if (!string.IsNullOrEmpty(text))
Directory.CreateDirectory(text);
File.Create(text + str).Close();
File.Delete(text + str);
return UploadTypeEnum.Direct;
} catch (Exception) {
return UploadTypeEnum.Web;
}
}
}
}