Ruta process taking long time in Java Workspace - Uima - uima

I tried to mark paragraph which endswith space. In Ruta workspace SpaceBeforeEnter rule ran quickly. But in Java workspace same rule taking more time to excecute. Used versions as follows,
uimaj-core version =>2.10.2, ruta-core version =>2.8.1 and ruta-core-ext version =>2.8.1 in both workspace. If I use the below in SCRIPT1, I'm not facing Time issue.
Rule
DECLARE SpaceBeforeEnter;
RETAINTYPE(BREAK,SPACE,MARKUP);
SPACE+?{-PARTOF(Footnote_Block),-PARTOF(Endnote_Block),-PARTOF(TAB),-PARTOF(SpaceBeforeEnter)} MARKUP*?{-PARTOF(Math),-PARTOF(IMG)->MARK(SpaceBeforeEnter,1)} #BREAK;
RETAINTYPE;
Code Snippet:
Initialise Engine and Run Process:
Ruta script1Ruta = callRuta(Path.Engine.SCRIPT1.ordinal());
if (script1Ruta.exception == null) {
script1Ruta.run();
if (script1Ruta.exception != null){
throw new Exception("Failed.");
}}
else {
throw new Exception("Failed.");
}
try {
Ruta script2Ruta = callRuta(script1Ruta.getCasIndex(), Path.Engine.SCRIPT2.ordinal());
script2Ruta.run();
}catch(Exception e){
logger.error(e.getMessage());
}
CallRuta():
private Ruta callRuta(int script1CasIndex, int engine) {
int[] engines = new int[1];
engines[0] = engine;
return (new Ruta(script1CasIndex, engines));
}
private Ruta callRuta(int engine) {
int[] engines = new int[1];
engines[0] = engine;
return (new Ruta(engines));
}
public Ruta(int casIndex, int[] engines) {
createEngines(engines.length);
this.engineIndex[0] = engines[0];
this.casIndex = casIndex;
if (casList.size() > casIndex) {
cas = casList.get(casIndex);
}
try {
File engineFile = Path.getEngineFiles(engineIndex[0]).get(0);
engine[0] = runScript(engineFile);
if (cas == null) { // Create new CAS for first script or if cas=null
cas = engine[0].newCAS();
artifact = readFile(Path.getXhtmlFile().getAbsolutePath());
cas.setDocumentText(artifact);
casList.add(cas);
} else {
logger.info("Existing CAS is used: " + casIndex);
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
run():
public void run() {
try {
engine[0].process(cas);
if (cas == null) {
logger.debug("OUPUT CAS is null");
} else {
logger.debug("OUTPUT CAS is NOT null");
}
NoException = true;
} catch (Exception e) {
logger.error(e.getMessage());
}}
runScript():
private AnalysisEngine runScript(File engineFile) throws Exception {
String path = new File(file.toURI()).getParentFile().getAbsolutePath();
String[] pathsArray = new String[] { path };
// override the values in the descriptor when creating the description
AnalysisEngineDescription desc = AnalysisEngineFactory.createEngineDescriptionFromPath(file.getAbsolutePath(),
RutaEngine.PARAM_SCRIPT_PATHS, pathsArray, RutaEngine.PARAM_DESCRIPTOR_PATHS, pathsArray,
RutaEngine.PARAM_RESOURCE_PATHS, pathsArray);
// in case the location of the descriptor is not known...
URL sourceUrl = desc.getSourceUrl();
path = new File(sourceUrl.toURI()).getParentFile().getAbsolutePath();
pathsArray = new String[] { path };
// set the values in the description
ConfigurationParameterSettings settings = desc.getAnalysisEngineMetaData().getConfigurationParameterSettings();
settings.setParameterValue(RutaEngine.PARAM_SCRIPT_PATHS, pathsArray);
settings.setParameterValue(RutaEngine.PARAM_DESCRIPTOR_PATHS, pathsArray);
settings.setParameterValue(RutaEngine.PARAM_RESOURCE_PATHS, pathsArray);
// override the values in the descriptor when creating the analysis
// engine
AnalysisEngine ae = AnalysisEngineFactory.createEngine(desc, RutaEngine.PARAM_SCRIPT_PATHS, pathsArray,
RutaEngine.PARAM_DESCRIPTOR_PATHS, pathsArray, RutaEngine.PARAM_RESOURCE_PATHS, pathsArray);
// set the values in the analysis engine and reconfigure it
ae.setConfigParameterValue(RutaEngine.PARAM_SCRIPT_PATHS, pathsArray);
ae.setConfigParameterValue(RutaEngine.PARAM_DESCRIPTOR_PATHS, pathsArray);
ae.setConfigParameterValue(RutaEngine.PARAM_RESOURCE_PATHS, pathsArray);
ae.reconfigure();
return ae; //returns Analysis Engine
}

Related

How to implement boolean retrieval using hitcollector in below scenario

I am running my code on TREC documents and right now implementing scoring scheme to get number of relevant documents. However now i want to implement boolean retrieval, I am trying to use HitCollector.
below is my code..
public class BatchSearch {
private BatchSearch() {}
/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
String usage =
"Usage:\tjava BatchSearch [-index dir] [-simfn similarity] [-field f] [-queries file]";
if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
System.out.println(usage);
System.out.println("Supported similarity functions:\ndefault: DefaultSimilary (tfidf)\n");
System.exit(0);
}
String index = "index";
String field = "contents";
String queries = null;
String simstring = "default";
for(int i = 0;i < args.length;i++) {
if ("-index".equals(args[i])) {
index = args[i+1];
i++;
} else if ("-field".equals(args[i])) {
field = args[i+1];
i++;
} else if ("-queries".equals(args[i])) {
queries = args[i+1];
i++;
} else if ("-simfn".equals(args[i])) {
simstring = args[i+1];
i++;
}
}
Similarity simfn = null;
if ("default".equals(simstring)) {
simfn = new DefaultSimilarity();
} else if ("bm25".equals(simstring)) {
simfn = new BM25Similarity();
} else if ("dfr".equals(simstring)) {
simfn = new DFRSimilarity(new BasicModelP(), new AfterEffectL(), new NormalizationH2());
} else if ("lm".equals(simstring)) {
simfn = new LMDirichletSimilarity();
}
if (simfn == null) {
System.out.println(usage);
System.out.println("Supported similarity functions:\ndefault: DefaultSimilary (tfidf)");
System.out.println("bm25: BM25Similarity (standard parameters)");
System.out.println("dfr: Divergence from Randomness model (PL2 variant)");
System.out.println("lm: Language model, Dirichlet smoothing");
System.exit(0);
}
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index)));
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(simfn);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
BufferedReader in = null;
if (queries != null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
} else {
in = new BufferedReader(new InputStreamReader(new FileInputStream("queries"), "UTF-8"));
}
QueryParser parser = new QueryParser(Version.LUCENE_41, field, analyzer);
while (true) {
String line = in.readLine();
if (line == null || line.length() == -1) {
break;
}
line = line.trim();
if (line.length() == 0) {
break;
}
String[] pair = line.split(" ", 2);
Query query = parser.parse(pair[1]);
doBatchSearch(in, searcher, pair[0], query, simstring);
}
reader.close();
}
/**
* This function performs a top-1000 search for the query as a basic TREC run.
*/
public static void doBatchSearch(BufferedReader in, IndexSearcher searcher, String qid, Query query, String runtag)
throws IOException {
// Collect enough docs to show 5 pages
TopDocs results = searcher.search(query, 1000);
ScoreDoc[] hits = results.scoreDocs;
HashMap<String, String> seen = new HashMap<String, String>(1000);
int numTotalHits = results.totalHits;
int start = 0;
int end = Math.min(numTotalHits, 1000);
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
String docno = doc.get("docno");
// There are duplicate document numbers in the FR collection, so only output a given
// docno once.
if (seen.containsKey(docno)) {
continue;
}
seen.put(docno, docno);
System.out.println(qid+" Q0 "+docno+" "+i+" "+hits[i].score+" "+runtag);
}
}
}
The scoring is done in doBatchSearch and now i want to implement HitCollector here.

wicket download output stream

I want to download csv file , i take the response content and write to it , apprently wicket write after me and the content iam getting is the page html where it should be my csv
I have seen in the example the usage of throw new AbortException();
I am using version 6.7 , do you know if my version wicket has somthing instead of it ?
or rather I am doing somthing wrong ....
can you please help me ...
add(new Link<Void>("export") {
#Override
public void onClick() {
WebResponse response = (WebResponse) getResponse();
response.setAttachmentHeader("export.csv");
response.setContentType("text/csv");
OutputStream out = getResponse().getOutputStream();
try {
c.exportData(dataSource.getListForExport(), columns, out);
} catch (Exception ex) {
System.err.println(ex);
}
}
});
public <T> void exportData(List<T> list, List<IGridColumn<IDataSource<T>, T, String>> columns, OutputStream outputStream)
throws IOException {
long startTime = System.nanoTime();
PrintWriter out = new PrintWriter(new OutputStreamWriter(outputStream, Charset.forName(characterSet)));
try {
if (isExportHeadersEnabled()) {
boolean first = true;
for (IGridColumn<IDataSource<T>, T, String> col : columns) {
if (first) {
first = false;
} else {
out.print(delimiter);
System.out.println(delimiter);
}
if (col.getId().equals("checkBox")) {
continue;
}
out.print(quoteValue(col.getId()));
System.out.println(col.getId());
}
out.print("\r\n");
System.out.println("\r\n");
}
Iterator<? extends T> rowIterator = list.iterator();
while (rowIterator.hasNext()) {
T row = rowIterator.next();
boolean first = true;
for (IGridColumn<IDataSource<T>, T, String> col : columns) {
if (first) {
first = false;
} else {
out.print(delimiter);
System.out.println(delimiter);
}
if (col.getId().equals("checkBox")) {
continue;
}
Object o = (new PropertyModel<>(row, col.getId())).getObject();// ((AbstractColumn<T,
if (o != null) {
Class<?> c = o.getClass();
String s;
IConverter converter = Application.get().getConverterLocator().getConverter(c);
if (converter == null) {
s = o.toString();
} else {
s = converter.convertToString(o, Session.get().getLocale());
}
out.print(quoteValue(s));
System.out.println(quoteValue(s));
}
}
out.print("\r\n");
System.out.println("\r\n");
}
} catch (Exception ex) {
System.out.println(ex);
} finally {
System.out.println(out);
out.close();
// measure
System.out.print(System.nanoTime() - startTime);
}
}
The best way to do this is using dynamic resources. I'll suggest you to read chapter "Resource managment with Wicket" of this magnific free Wicket guide: https://code.google.com/p/wicket-guide/.
Here you have a similar example given in this guide in the section "Custom resources".
public class RSSProducerResource extends AbstractResource {
#Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
ResourceResponse resourceResponse = new ResourceResponse();
resourceResponse.setContentType("text/xml");
resourceResponse.setTextEncoding("utf-8");
resourceResponse.setWriteCallback(new WriteCallback()
{
#Override
public void writeData(Attributes attributes) throws IOException
{
OutputStream outputStream = attributes.getResponse().getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
SyndFeedOutput output = new SyndFeedOutput();
try {
output.output(getFeed(), writer);
} catch (FeedException e) {
throw new WicketRuntimeException("Problems writing feed to response...");
}
}
});
return resourceResponse;
}
// method getFeed()...
}
And then you need to add the link in the desired page or component:
add(new ResourceLink("rssLink", new RSSProducerResource()));

Prevent sending email and show message via plug-in

I am writing crm2011 plugin in "Email" entity with "Send" Message of Pre_operation. What i want to do is when i click "Send" button in email entity, I do the necessary checking before send. If the checking is not correct, I want to prevent and stop the sending email and show "the alert message" and stop the second plugin(this plugin send email and create the associated entity to convert "Case"). Please give me some suggestion for that plugin?
Should i use pre-Validation stage or Pre_operation state? And how can I return false to stop plugin.
public void Execute(IServiceProvider serviceProvider)
{
try
{
string message = null;
_serviceProvider = serviceProvider;
_context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_currentUser = _context.UserId;
message = _context.MessageName.ToLower();
if (message == "send")
{
if (_context.InputParameters != null && _context.InputParameters.Contains("EmailId"))
{
object objEmailId = _context.InputParameters["EmailId"];
if (objEmailId != null)
{
_emailId = new Guid(objEmailId.ToString());
FindEmailInfo();
if (_email != null)
{
if (_email.Attributes.Contains("description") && _email.Attributes["description"] != null)//Email descritpion is not null
{
string emaildescription = StripHTML();
//Find KB Article prefix no in system config entity
serviceguideprefix = "ServiceGuidesPrefix";
QueryByAttribute query = new QueryByAttribute("ppp_systemconfig");
query.ColumnSet = new ColumnSet(true);
query.AddAttributeValue(sysconfig_name, serviceguideprefix);
EntityCollection sysconfig = _service.RetrieveMultiple(query);
if (sysconfig.Entities.Count > 0)
{
Entity e = sysconfig.Entities[0];
if (e.Attributes.Contains("ppp_value"))
{
ppp_value = e.Attributes["ppp_value"].ToString();
}
}
if (ppp_value != null && ppp_value != string.Empty)
{
//var matches = Regex.Matches(emaildescription, #"KBA-\d*-\w*").Cast<Match>().ToArray();
var matches = Regex.Matches(emaildescription, ppp_value + #"-\d*-\w*").Cast<Match>().ToArray();
//ReadKBNo(emaildescription);
foreach (Match kbnumber in matches)
{
EntityCollection kbarticlecol = FindKBArticleIds(kbnumber.ToString());
if (kbarticlecol.Entities.Count > 0)
{
Entity kbariticle = kbarticlecol.Entities[0];
if (kbariticle.Attributes.Contains("mom_internalkm"))
{
bool internalserviceguide = (bool)kbariticle.Attributes["mom_internalkm"];
if (internalserviceguide) found = true;
else found = false;
}
else found = false;
}
}
}
if (found)
{
//-----
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
Well stopping the plugin is dead easy you just throw InvalidPluginException, the message you give it will be shown to the user in a alert window. You will have to do this on the pre of the send. In this case I don't think it will matter if its pre-validation or pre-operation.
Edit:
Yes, you should throw an InvalidPluginException even if no exception has happened in code. I accept this isnt what we would normally do, but its the way its meant to work. Msdn has more details: http://msdn.microsoft.com/en-us/library/gg334685.aspx
So for example the code would look like:
public void Execute(IServiceProvider serviceProvider)
{
try
{
//This is where we validate the email send
if(emailIsOkay)
{
//Do something
}
else if(emailIsNotOkay)
{
//Throw and exception that will stop the plugin and the message will be shown to the user (if its synchronous)
throw new InvalidPluginExecutionException("Hello user, your email is not correct!!");
}
}
catch (InvalidPluginExecutionException invalid)
{
//We dont to catch exception for InvalidPluginExecution, so just throw them on
throw;
}
catch (Exception ex)
{
//This exception catches if something goes wrong in the code, or some other process.
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}

Dynamics CRM 4.0 plugin fails when triggered by API

I have a plugin registered for when an account is created or updated, this is registered for the post stage.
The plugin works fine when a user creates or updates an account through the CRM interface, however when an account is created uging the API the plugin fails with the ever helpful 'server was unable to process the request' message. if an account is updated through the api the plugin also works correctly.
anyone have any ideas why?
UPDATE:
here is the create code
account = new CrmService.account();
account.ownerid = new CrmService.Owner();
account.ownerid.Value = new Guid("37087BC2-F2F0-DC11-A856-001E0B617486");
account.ownerid.type = CrmService.EntityName.systemuser.ToString();
account.name = model.CompanyName;
account.address1_line1 = model.Address1;
account.address1_line2 = model.Address2;
account.address1_stateorprovince = model.County;
account.address1_country = model.Country;
account.address1_city = model.TownCity;
account.address1_postalcode = model.PostCode;
account.new_companytype = new CrmService.Picklist();
switch (model.SmeType)
{
case SmeType.Micro:
account.new_companytype.Value = 1;
break;
case SmeType.Small:
account.new_companytype.Value = 2;
break;
case SmeType.Medium:
account.new_companytype.Value = 3;
break;
default:
break;
}
account.new_balancesheettotal = new CrmService.CrmMoney();
account.new_balancesheettotal.Value = preQualModel.BalanceSheetGBP;
account.revenue = new CrmService.CrmMoney();
account.revenue.Value = preQualModel.SalesTurnoverGBP;
if (model.Website != null)
{
account.websiteurl = model.Website.ToString();
}
account.numberofemployees = new CrmService.CrmNumber();
account.numberofemployees.Value = (int)preQualModel.NumEmployees;
accountGuid = svc.Create(account);
account.accountid = new CrmService.Key();
account.accountid.Value = accountGuid;
Here is the plugin code:
public void Execute(IPluginExecutionContext context)
{
DynamicEntity entity = null;
// Check if the InputParameters property bag contains a target
// of the current operation and that target is of type DynamicEntity.
if (context.InputParameters.Properties.Contains(ParameterName.Target) &&
context.InputParameters.Properties[ParameterName.Target] is DynamicEntity)
{
// Obtain the target business entity from the input parmameters.
entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target];
// TODO Test for an entity type and message supported by your plug-in.
if (entity.Name != EntityName.account.ToString()) { return; }
// if (context.MessageName != MessageName.Create.ToString()) { return; }
}
else
{
return;
}
if (entity!=null && !entity.Properties.Contains("address1_postalcode"))
{
return;
}
if (context.Depth > 2)
{
return;
}
try
{
// Create a Microsoft Dynamics CRM Web service proxy.
// TODO Uncomment or comment out the appropriate statement.
// For a plug-in running in the child pipeline, use this statement.
// CrmService crmService = CreateCrmService(context, true);
// For a plug-in running in the parent pipeline, use this statement.
ICrmService crmService = context.CreateCrmService(true);
#region get erdf area from database
string postCode = entity.Properties["address1_postalcode"].ToString();
postCode = postCode.Replace(" ", ""); //remove spaces, db stores pcodes with no spaces, users usually enter them, e.g b4 7xg -> b47xg
string erdfArea = "";
SqlConnection myConnection = new SqlConnection(#"REDACTED");
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select ErdfAreaType from dim.Locality WHERE PostCode = '" + postCode+"'",
myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
erdfArea = myReader["ErdfAreaType"].ToString();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
#endregion
entity.Properties["new_erdfarea"] = erdfArea;
crmService.Update(entity);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
throw new InvalidPluginExecutionException(
String.Format("An error occurred in the {0} plug-in.",
this.GetType().ToString()),
ex);
}
}
Sometimes it can be difficult to see the actual source of an error in plugins. In moments like this tracing is your friend. You can use this tool to enable tracing. When you have the trace files, try to search them for the error you got in your exception. This should tell you more details about what is failing.
Turns out this was due to me expecting data that was not there due to some weird behaviour in CRM.
I was taking the dynamicEntity passed to the plugin like so
entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target];
But this was missing critical things like accountid. fixed it by using the PostEntityImage entity instead, which had all of the expected data like so
entity = (DynamicEntity)context.PostEntityImages[ParameterName.Target];

build index using lucene.net 2.9.2.2

I have to use lucene.net 2.9.2.2 with NHibernate 3.0. I have started to edit this old code:
public void BuildSearchIndex()
{
FSDirectory entityDirectory = null;
IndexWriter writer = null;
var entityType = typeof(MappedSequence);
var indexDirectory = new DirectoryInfo(GetIndexDirectory());
if (indexDirectory.Exists)
{
indexDirectory.Delete(true);
}
try
{
entityDirectory = FSDirectory.GetDirectory(Path.Combine(indexDirectory.FullName, entityType.Name), true);
writer = new IndexWriter(entityDirectory, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29), true, IndexWriter.MaxFieldLength.UNLIMITED);
}
finally
{
if (entityDirectory != null)
{
entityDirectory.Close();
}
if (writer != null)
{
writer.Close();
}
}
IFullTextSession fullTextSession = Search.CreateFullTextSession(this.Session);
// Iterate through Suppliers and add them to Lucene's index
foreach (MappedSequence instance in Session.CreateCriteria(typeof(MappedSequence)).List<MappedSequence>())
{
fullTextSession.Index(instance);
}
}
private string GetIndexDirectory()
{
INHSConfigCollection nhsConfigCollection = CfgHelper.LoadConfiguration();
string property = nhsConfigCollection.DefaultConfiguration.Properties["hibernate.search.default.indexBase"];
var fi = new FileInfo(property);
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fi.Name);
}
to build the index. The line:
FSDirectory.GetDirectory(Path.Combine(indexDirectory.FullName, entityType.Name), true);
still uses obsolete code. Could anyone be so kind and point out the necessary change. Thanks.
Christian
PS
Try using FSDirectory.Open(path) instead.