NCBI C++ ToolKit
search_tool_base.cpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 /* $Id: search_tool_base.cpp 40276 2018-01-19 17:40:36Z katargir $
2  * ===========================================================================
3  *
4  * PUBLIC DOMAIN NOTICE
5  * National Center for Biotechnology Information
6  *
7  * This software/database is a "United States Government Work" under the
8  * terms of the United States Copyright Act. It was written as part of
9  * the author's official duties as a United States Government employee and
10  * thus cannot be copyrighted. This software/database is freely available
11  * to the public for use. The National Library of Medicine and the U.S.
12  * Government have not placed any restriction on its use or reproduction.
13  *
14  * Although all reasonable efforts have been taken to ensure the accuracy
15  * and reliability of the software and data, the NLM and the U.S.
16  * Government do not and cannot warrant the performance or results that
17  * may be obtained by using this software or data. The NLM and the U.S.
18  * Government disclaim all warranties, express or implied, including
19  * warranties of performance, merchantability or fitness for any particular
20  * purpose.
21  *
22  * Please cite the author in any work or product based on this material.
23  *
24  * ===========================================================================
25  *
26  * Authors: Andrey Yazhuk
27  *
28  * File Description:
29  *
30  */
31 
32 #include <ncbi_pch.hpp>
33 
34 
36 
38 
40 
43 
44 
47 
48 ///////////////////////////////////////////////////////////////////////////////
49 /// IDMSearchTool
50 
51 static const char* kDefaultErrMessage = "CSearchToolBase: Tool Execution Failed";
52 
54 : m_ReportPeriod(1)
55 {
56 }
57 
58 
60 {
61 
62 }
63 
65 {
66  switch (ptype)
67  {
68  case eExactMatch: return "eExactMatch";
69  case eWildcard: return "eWildcard";
70  case eRegexp: return "eRegexp";
71  case eNamed: return "eNamed";
72  default: return "Unknown Search Pattern";
73  }
74 }
75 
76 
79  &CSearchToolBase::OnAJNotification)
81  &CSearchToolBase::OnProgress)
83 
84 
86 {
87  if ((GetFlags() & IDMSearchTool::eCache) &&
88  !(GetFlags() & IDMSearchTool::eAutorun) && m_Cache) {
89  CRef<CSearchJobBase> job = x_CreateJob(query);
90  if(job) {
92  new CDMSearchResult("",
93  job->x_GetNewOLTModel(),
94  new CObjectList(*m_Cache))
95  );
96  //res->m_QueryDescr = GetDescr();
97  listener.OnSearchFinished(*res);
98  }
99  return true;
100  }
101  return false;
102 }
103 
105 {
107  if(job) {
108  try {
109  // setup additional stuff
110  job->SetFilters(m_Filters);
111 
112  string descr = job->GetDescr();
113 
114  LOG_POST(Info << descr);
115 
116  /// launch on ThreadPool, receive notifications, no progress reports
117  /// delete the Job when completed
119  int job_id = disp.StartJob(*job, "ThreadPool", *this, m_ReportPeriod, true);
120 
121  /// create session record
122  SSession* session = new SSession;
123  session->m_Query = &query;
124  session->m_Listener = &listener;
125  session->m_JobID = job_id;
126  session->m_Descr = descr;
127  m_Sessions.push_back(session);
128 
129  //LOG_POST("Started " << descr);
130  return true;
131  } catch(CAppJobException& e) {
132  ERR_POST("CSearchToolBase::StartSearch() - Failed to execute query");
133  LOG_POST(Error << e.ReportAll());
134  // TODO pass error msg to UI
135  return false;
136  }
137  } else {
138  // throw?
139  return false;
140  }
141 }
142 
143 
145 {
146  int index = x_GetSessionIndexByListener(listener);
147 
148  if(index == -1) {
149  // _ASSERT(false);
150  // ERR_POST("CSearchToolBase::CancelSearch() - invalid listener");
151  } else {
152  SSession* session = m_Sessions[index];
153  try {
155  disp.DeleteJob(session->m_JobID);
156 
157  m_Sessions.erase(m_Sessions.begin() + index);
158  delete session;
159  //LOG_POST("Canceled Job" );
160  return true;
161  } catch (CAppJobException&) {
162  ERR_POST("CSearchToolBase::CancelSearch() - Failed to cancel search");
163  // TODO pass error msg to UI
164  }
165  }
166  return false;
167 }
168 
169 
171 {
172  CAppJobNotification* notn = dynamic_cast<CAppJobNotification*>(evt);
173  _ASSERT(notn);
174 
175  if(notn) {
176  int job_id = notn->GetJobID();
177  int s_i = x_GetSessionIndexByID(job_id);
178  if(s_i == -1) {
179  ERR_POST("CSearchToolBase::OnAJNotification() - unknown Job ID " << job_id);
180  } else {
181  SSession* session = m_Sessions[s_i];
182 
183  switch(notn->GetState()) {
184  case IAppJob::eCompleted:
185  x_OnJobCompleted(*notn, *session);
186  break;
187  case IAppJob::eFailed:
188  x_OnJobFailed(*notn, *session);
189  break;
190  case IAppJob::eCanceled:
191  x_OnJobCanceled(*notn, *session);
192  break;
193  default:
194  session = NULL;
195  }
196 
197  if(session) {
198  m_Sessions.erase(m_Sessions.begin() + s_i);
199  delete session;
200  }
201  }
202  }
203 }
204 
205 
207 {
208  CAppJobNotification* notn = dynamic_cast<CAppJobNotification*>(evt);
209 
210  _ASSERT(notn);
211 
212  if(notn) {
213  int job_id = notn->GetJobID();
214  int s_i = x_GetSessionIndexByID(job_id);
215  if(s_i == -1) {
216  ERR_POST("CSearchToolBase::OnProgress() - unknown Job ID " << job_id);
217  } else {
218  SSession* session = m_Sessions[s_i];
219 
221  const CDMSearchProgress* progress =
222  dynamic_cast<const CDMSearchProgress*>(prg.GetPointer());
223 
225  if (progress) {
226  CRef<CDMSearchResult> ref = progress->m_Result;
227  result = ref.GetPointer();
228  }
229 
230  _ASSERT(progress);
231  if(progress && result) {
232  string s = progress->GetText();
233  session->m_Listener->OnSearchProgress(*result, s);
234  }
235  }
236  }
237 }
238 
239 
241 {
242  string s;
243  int index = x_GetSessionIndexByListener(form);
244  if(index != -1) {
245  s = m_Sessions[index]->m_Descr;
246  }
247  return s;
248 }
249 
250 
252 {
253  for( size_t i = 0; i < m_Sessions.size(); i++) {
254  if(m_Sessions[i]->m_JobID == job_id) {
255  return (int)i;
256  }
257  }
258  return -1;
259 }
260 
261 
263 {
264  for( size_t i = 0; i < m_Sessions.size(); i++) {
265  if(m_Sessions[i]->m_Query.GetPointer() == &query) {
266  return (int)i;
267  }
268  }
269  return -1;
270 }
271 
272 
274 {
275  for( size_t i = 0; i < m_Sessions.size(); i++) {
276  if(m_Sessions[i]->m_Listener == &listener) {
277  return (int)i;
278  }
279  }
280  return -1;
281 }
282 
283 
285 {
286  CRef<CObject> res_obj = notify.GetResult();
287  CDMSearchResult* result = dynamic_cast<CDMSearchResult*>(res_obj.GetPointer());
288  if(result) {
290 
292  m_Cache.Reset(new CObjectList(*result->GetObjectList()));
293  }
294  //LOG_POST("Job Completed ");
295  } else {
296  m_Cache.Reset();
297  session.m_Listener->OnSearchFailed("Internal error - no results available");
298  ERR_POST("CSearchToolBase::x_OnJobCompleted() notification for job "
299  << session.m_JobID << " does not contain results.");
300  }
301 }
302 
303 
305 {
306  m_Cache.Reset();
307  CConstIRef<IAppJobError> err = notify.GetError();
308  if(err) {
309  session.m_Listener->OnSearchFailed(err->GetText());
310  } else {
311  session.m_Listener->OnSearchFailed("Internal error - Search Failed");
312  ERR_POST("CSearchToolBase::x_OnJobFailed() notification for job "
313  << session.m_JobID << " does not have an error object");
314  }
315 }
316 
317 
319 {
320  //LOG_POST("CSearchToolBase::x_OnJobCanceled()");
321  m_Cache.Reset();
322  session.m_Listener->OnSearchCanceled();
323 }
324 
325 
327 {
328  return IDMSearchTool::eCache;
329 }
330 
332 {
333  return m_Conversions;
334 }
335 
337 {
338  return m_Filters;
339 }
340 
342 {
343  return m_Filters;
344 }
345 
346 ///////////////////////////////////////////////////////////////////////////////
347 /// CSearchJobBase
348 
349 /// override the constructor, initialize m_Descr
351 {
352  m_MaxResultsCount = 0;
353 }
354 
355 
357 {
358 }
359 
360 
362 {
363  if(x_ValidateParams()) {
364  x_PrepareSearch();
365 
367  if(state == eCompleted) {
369  }
370  return state;
371  }
372  else {
373  LOG_POST(Warning << m_Descr << " -- " << "Parameter validation failed!");
374  }
375  return eFailed;
376 }
377 
378 
380 {
381  CMutexGuard Guard(m_Mutex);
382 
383  m_ResultsCount = 0;
384  m_AccList.Clear();
386 
387  m_ProgressStr = "";
388 
389  // create new Temp Result object
392  );
393 
394  //m_TempResult->m_Handler = x_GetColumnHandler();
395 
397 
398  /// reset Final Result and Error objects
399  m_Result.Reset();
401 }
402 
403 
405 {
406  CMutexGuard Guard(m_Mutex);
407 
408  /// flush the last portion
411 
414 
415  if (m_MaxResultsCount > 0) { // max result limitation exists?
417  m_Result->SetIncomplete(true);
419  }
420  }
421 
422  m_ProgressStr = "Finished.";
423 }
424 
425 
427 {
428  //override in derived classes if you need to add columns
429 }
430 
431 
432 
433 
435 {
436  CMutexGuard Guard(m_Mutex); // synchronize
437 
439  if(m_TempResult) {
440  CObjectList *obj_list = m_TempResult->GetObjectList();
441  res.Reset(
444  new CObjectList( *obj_list)
445  )
446  );
447 
448  //res->m_Handler = x_GetColumnHandler();
449  }
450 
452  return pr;
453 }
454 
455 
457 {
458  CMutexGuard Guard(m_Mutex); // synchronize
459 
461 }
462 
463 
465 {
467 }
468 
469 
471 {
472  return m_Descr;
473 }
474 
475 /*
476 IObjectColumnHandler* CSearchJobBase::x_GetColumnHandler() const
477 {
478  /// no handler by default, override this function if needed
479  return NULL;
480 }
481 */
482 
484 {
485  return NULL;
486 }
487 
CAppJobDispatcher.
CAppJobError Default implementation for IAppJobError - encapsulates a text error message.
IAppJobListener Interface for components that need to be notified about changes in Jobs.
CAppJobNotification Notification send by CAppJobEventTranslator.
CDMSearchProgress CDMSearchProgress represents the specialized progress report that may contain inter...
CRef< CDMSearchResult > m_Result
CDMSearchResult - result object delivered using job progress object.
CObjectList * GetObjectList()
const string & GetQueryDescr() const
void SetMaxSearchResult(size_t maxsr)
void SetIncomplete(bool incomplete=true)
CEventHandler.
CEvent - generic event implementation TODO TODO - Attachments.
Definition: event.hpp:86
CObjectListTableModel.
CObjectList Data structure representing a list of CObjects with associated Scopes and other optional ...
Definition: object_list.hpp:63
void Append(const CObjectList &list)
adds rows from the given list, the lists must have identical sets of columns
void ClearRows()
CRef –.
Definition: ncbiobj.hpp:618
int m_MaxResultsCount
Max possible results count.
CRef< CDMSearchResult > m_TempResult
holds temporary results, guarded by Mutex
string m_Descr
human-readable description of the Job
int m_ResultsCount
total number of results
virtual bool x_ValidateParams()=0
returns true if Job params are correct, implement in derived classes
virtual EJobState x_DoSearch()=0
performs searching, assuming that params are correct; Implement in derived classes
virtual CObjectListTableModel * x_GetNewOLTModel() const
factory method creating new column handler for CObjectListWidget
virtual ~CSearchJobBase()
CRef< CDMSearchResult > m_Result
guarded by Mutex
virtual CConstIRef< IAppJobError > GetError()
Returns IAppJobError object describing internal error that caused the Job to fail.
virtual EJobState Run()
Function that does all the useful work, called by the Engine.
virtual void x_TransferResults()
transfer data from Temp Results to Final
virtual CRef< CObject > GetResult()
Returns the Job Result.
virtual void x_SetupColumns(CObjectList &obj_list)
add custom columns if needed
CMutex m_Mutex
synchronizes access to the Job members
CRef< CAppJobError > m_Error
virtual string GetDescr() const
Returns a human readable description of the Job (optional)
virtual void x_PrepareSearch()
CSearchJobBase()
CSearchJobBase.
CObjectList m_AccList
accumulates found objects before they are transferred to m_ResultList
virtual CConstIRef< IAppJobProgress > GetProgress()
return progress object, the function shall be synchronized internally.
CSearchToolBase.
virtual IDMSearchTool::TConversions & GetConversions(void)
list of acceptable feat types top convert and default type
void OnProgress(CEvent *evt)
virtual void x_OnJobCanceled(CAppJobNotification &notify, SSession &session)
virtual string GetJobDescr(IDMSearchFormController &form)
void OnAJNotification(CEvent *evt)
CAppJobDispatcher notification handler.
virtual void x_OnJobCompleted(CAppJobNotification &notify, SSession &session)
IDMSearchTool::TFilters m_Filters
int x_GetSessionIndexByQuery(IDMSearchQuery &query)
virtual bool CancelSearch(IDMSearchFormController &listener)
virtual IDMSearchTool::TFilters & SetFilters()
virtual CRef< CSearchJobBase > x_CreateJob(IDMSearchQuery &query)=0
create a job based on the given query, override in derived classes
virtual void x_OnJobFailed(CAppJobNotification &notify, SSession &session)
int x_GetSessionIndexByListener(IDMSearchFormController &listener)
CRef< CObjectList > m_Cache
virtual bool StartSearch(IDMSearchQuery &query, IDMSearchFormController &listener)
Starts search Job, the job is identified by the query object.
virtual const IDMSearchTool::TFilters & GetFilters(void) const
list of all tool-provided filters
static string GetPatternTypeStr(EPatternType ptype)
String representation of pattern type.
vector< SSession * > m_Sessions
virtual IDMSearchTool::TUIToolFlags GetFlags(void)
special flags
IDMSearchTool::TConversions m_Conversions
virtual ~CSearchToolBase()
int x_GetSessionIndexByID(int job_id)
IDMSearchFormController - interface representing an entity that controls the lifecycle of search Form...
virtual void OnSearchProgress(CDMSearchResult &, const string &)
virtual void OnSearchCanceled()
virtual void OnSearchFinished(CDMSearchResult &)
virtual void OnSearchFailed(const string &)
IDMSearchQuery - abstract data mining query.
#define NULL
Definition: ncbistd.hpp:225
#define ERR_POST(message)
Error posting with file, line number information but without error codes.
Definition: ncbidiag.hpp:186
#define LOG_POST(message)
This macro is deprecated and it's strongly recomended to move in all projects (except tests) to macro...
Definition: ncbidiag.hpp:226
void Error(CExceptionArgs_Base &args)
Definition: ncbiexpt.hpp:1197
void Warning(CExceptionArgs_Base &args)
Definition: ncbiexpt.hpp:1191
void Info(CExceptionArgs_Base &args)
Definition: ncbiexpt.hpp:1185
CConstIRef< IAppJobError > GetError() const
returns non-null pointer only if job Failed
static CAppJobDispatcher & GetInstance()
CRef< CObject > GetResult() const
returns non-null pointer only if Completed or Running and has temporary results available
bool DeleteJob(TJobID job_id)
when a Job is deleted the listener is not notified
EJobState
Job states (describe FSM)
Definition: app_job.hpp:86
TJobID StartJob(IAppJob &job, const string &engine_name, IEngineParams *params=NULL)
Starts a Job on the specified engine in "passive mode" - no notifications or progress reports will be...
CConstIRef< IAppJobProgress > GetProgress() const
returns non-null pointer only if notification type is eProgress
#define END_EVENT_MAP()
Ends definition of Command Map.
#define BEGIN_EVENT_MAP(thisClass, baseClass)
Begins definition of Command Map for CEventHandler-derived class.
TJobState GetState() const
virtual string GetText() const override
returns a text string describing current state
@ eCanceled
Definition: app_job.hpp:91
@ eCompleted
Definition: app_job.hpp:89
@ eFailed
Definition: app_job.hpp:90
TObjectType * GetPointer(void) const THROWS_NONE
Get pointer,.
Definition: ncbiobj.hpp:1684
TObjectType * GetPointer(void) THROWS_NONE
Get pointer,.
Definition: ncbiobj.hpp:998
void Reset(void)
Reset reference object.
Definition: ncbiobj.hpp:773
#define END_NCBI_SCOPE
End previously defined NCBI scope.
Definition: ncbistl.hpp:103
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
Definition: ncbistl.hpp:100
int i
USING_SCOPE(objects)
ON_EVENT(CAppJobNotification, CAppJobNotification::eStateChanged, &CSearchToolBase::OnAJNotification) ON_EVENT(CAppJobNotification
static const char * kDefaultErrMessage
IDMSearchTool.
IDMSearchFormController * m_Listener
CIRef< IDMSearchQuery > m_Query
static string query
#define _ASSERT
else result
Definition: token2.c:20
Modified on Fri Dec 08 08:20:38 2023 by modify_doxy.py rev. 669887