void TestStateA::event1(Service& sv, Event& ev)
{
	printf("TestStateA::event1()\n");
	TimerManager::getInstance().setTimer(*((TestService*)&sv), "test", 1, 1000*2);
	sv.changeState("TestStateB");
}
TEST_CASE( "overwrite existing resource", "[resource]" )
{
    auto initial_resource = make_shared< Resource >( );
    initial_resource->set_path( "TestResource" );
    initial_resource->set_method_handler( "GET", json_get_handler );
    
    auto secondary_resource = make_shared< Resource >( );
    secondary_resource->set_path( "TestResource" );
    secondary_resource->set_method_handler( "GET", xml_get_handler );
    
    auto settings = make_shared< Settings >( );
    settings->set_port( 1984 );
    
    shared_ptr< thread > worker = nullptr;
    
    Service service;
    service.publish( initial_resource );
    service.publish( secondary_resource );
    service.set_ready_handler( [ &worker ]( Service & service )
    {
        worker = make_shared< thread >( [ &service ] ( )
        {
            Request request;
            request.set_port( 1984 );
            request.set_host( "localhost" );
            request.set_path( "/TestResource" );

            auto response = Http::sync( request );
            
            REQUIRE( 401 == response->get_status_code( ) );
            
bool LocalSharpening::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Local Sharpening", "app", "08BB9B79-5D24-4AB0-9F35-92DE77CED8E7");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   EncodingType ResultType = pDesc->getDataType();
   if (pDesc->getDataType() == INT4SCOMPLEX)
   {
      ResultType = INT4SBYTES;
   }
   else if (pDesc->getDataType() == FLT8COMPLEX)
   {
      ResultType = FLT8BYTES;
   }

   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BSQ);
   DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Local_Sharpening_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType));
   if (pResultCube.get() == NULL)
   {
      std::string msg = "A raster cube could not be created.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

   Service<DesktopServices> pDesktop;
   LocalSharpeningDlg dlg(pDesktop->getMainWidget());
   int stat = dlg.exec();
   if (stat != QDialog::Accepted)
   {
	   return true;
   }
   double contrastVal = dlg.getContrastValue();
   int nFilterType = dlg.getCurrentFilterType();
   int windowSize = dlg.getCurrentWindowSize();
   windowSize = (windowSize-1)/2;

   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Local sharpening", row * 100 / pDesc->getRowCount(), NORMAL);
      }
      if (isAborted())
      {
         std::string msg = getName() + " has been aborted.";
         pStep->finalize(Message::Abort, msg);
         if (pProgress != NULL)
         {
            pProgress->updateProgress(msg, 0, ABORT);
         }
         return false;
      }
      if (!pDestAcc.isValid())
      {
         std::string msg = "Unable to access the cube data.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }
      for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
		  if (nFilterType == 0)
		  {
			  switchOnEncoding(ResultType, localAdaptiveSharpening, pDestAcc->getColumn(), pSrcAcc, row, col,
                               pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), windowSize, contrastVal);
		  }
		  else
		  {
           
			  switchOnEncoding(ResultType, localExtremeSharpening, pDestAcc->getColumn(), pSrcAcc, row, col,
                               pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), windowSize);
		  }
		  pDestAcc->nextColumn();
      }

      pDestAcc->nextRow();
   }


   if (!isBatch())
   {
      Service<DesktopServices> pDesktop;

      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));

      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         std::string msg = "Unable to create view.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }

      pView->setPrimaryRasterElement(pResultCube.get());
      pView->createLayer(RASTER, pResultCube.get());
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Local sharpening is compete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Local sharpening Result", pResultCube.release());

   pStep->finalize();


   return true;
}
Ejemplo n.º 4
0
ElmDlg::ElmDlg(SpatialDataView* pView, ElmInteractive* pElmInteractive, QWidget* pParent) :
   QDialog(pParent),
   mPixelOffset(1.0, 1.0),
   mMaxDisplayedPixels(10000),
   mCurrentIndex(-1),
   mpElmInteractive(pElmInteractive),
   mpView(pView, SIGNAL_NAME(Subject, Deleted), Slot(this, &ElmDlg::viewDeleted))
{
   // Initialization
   VERIFYNRV(mpView.get() != NULL);
   VERIFYNRV(mpElmInteractive != NULL);
   setWindowTitle(QString::fromStdString("Empirical Line Method - " + mpView->getDisplayName()));
   mpAoiElement.addSignal(SIGNAL_NAME(Subject, Modified), Slot(this, &ElmDlg::aoiModified));
   mpAoiElement.addSignal(SIGNAL_NAME(Subject, Deleted), Slot(this, &ElmDlg::aoiDeleted));

   // "Use Existing Gains/Offsets File" Layout Begin
   mpExistingFileBrowser = new FileBrowser;

   QHBoxLayout* pUseExistingFileLayout = new QHBoxLayout;
   pUseExistingFileLayout->addWidget(mpExistingFileBrowser);

   QGroupBox* pUseExistingFileGroup = new QGroupBox;
   pUseExistingFileGroup->setLayout(pUseExistingFileLayout);
   pUseExistingFileGroup->setEnabled(false);
   // "Use Existing Gains/Offsets File" Layout End


   // Element Layout Begin
   mpElementComboBox = new QComboBox;
   mpElementComboBox->setToolTip("This is the list of available ELM Elements.");
   mpElementComboBox->setWhatsThis("This is the list of available ELM Elements. "
      "ELM elements are simply a group of selected pixels, similar to an AOI, that specify the location "
      "of an object whose signature matches a corresponding input reflectance signature. "
      "At least two elements must be created to run the ELM algorithm.");

   QPushButton* pNewElementButton = new QPushButton("New Element");
   pNewElementButton->setToolTip("Click this button to create a new ELM element.");
   pNewElementButton->setWhatsThis("Click this button to create a new ELM element. "
      "Pixels must be selected and a corresponding signature must be selected for each element. "
      "At least two elements must be created to run the ELM algorithm.");

   QPushButton* pDeleteElementButton = new QPushButton("Delete Element");
   pDeleteElementButton->setToolTip("Click this button to delete the currently selected ELM Element.");
   pDeleteElementButton->setWhatsThis("Click this button to delete the currently selected ELM Element. "
      "The Element will be removed from the list and its pixels will be deleted from the scene.");

   QVBoxLayout* pElementLayout = new QVBoxLayout;
   pElementLayout->addWidget(mpElementComboBox);
   pElementLayout->addWidget(pNewElementButton);
   pElementLayout->addWidget(pDeleteElementButton);

   QGroupBox* pElementGroup = new QGroupBox("Current Element");
   pElementGroup->setLayout(pElementLayout);
   // Element Layout End


   // Pixel Layout Begin
   mpPixelList = new QListWidget;
   mpPixelList->setSortingEnabled(false);
   mpPixelList->setSelectionMode(QAbstractItemView::ExtendedSelection);
   mpPixelList->setToolTip("When pixels in the scene are selected, their coordinates are listed in this box.");
   mpPixelList->setWhatsThis("When pixels in the scene are selected, their coordinates are listed in this box. "
      "To remove pixels from the list, highlight the pixels to remove and click the \"Delete Pixels\" button.");

   QPushButton* pDeletePixelButton = new QPushButton("Delete Pixels");
   pDeletePixelButton->setToolTip("Click this button to exclude the currently selected "
      "pixel(s) in the list from any further processing.");
   pDeletePixelButton->setWhatsThis("Click this button to exclude the currently selected "
      "pixel(s) in the list from any further processing. The pixels will be removed from "
      "the list so that they cannot be considered during execution.");

   QVBoxLayout* pPixelLayout = new QVBoxLayout;
   pPixelLayout->addWidget(mpPixelList);
   pPixelLayout->addWidget(pDeletePixelButton);

   QGroupBox* pPixelGroup = new QGroupBox(QString("Pixels (Up to %1 displayed)").arg(mMaxDisplayedPixels));
   pPixelGroup->setLayout(pPixelLayout);
   // Pixel Layout End


   // Signature Layout Begin
   mpSignature = new QLineEdit;
   mpSignature->setReadOnly(true);

   QPushButton* pSignatureButton = new QPushButton("Change...");
   pSignatureButton->setToolTip("Select the corresponding reflectance signature for the selected Element.");
   pSignatureButton->setWhatsThis("Select the corresponding reflectance signature for the selected Element. ");

   QHBoxLayout* pSignatureLayout = new QHBoxLayout;
   pSignatureLayout->addWidget(mpSignature);
   pSignatureLayout->addWidget(pSignatureButton);

   QGroupBox* pSignatureGroup = new QGroupBox("Signature");
   pSignatureGroup->setLayout(pSignatureLayout);
   // Signature Layout End


   QGridLayout* pCalculateLayout = new QGridLayout;
   pCalculateLayout->addWidget(pElementGroup, 1, 0);
   pCalculateLayout->addWidget(pPixelGroup, 1, 1, 2, 1);
   pCalculateLayout->addWidget(pSignatureGroup, 3, 0, 1, 3);

   QGroupBox* pCalculateGroup = new QGroupBox;
   pCalculateGroup->setLayout(pCalculateLayout);
   pCalculateGroup->setEnabled(false);
   // "Calculate Gains/Offsets" Layout End


   // Button Box Begin
   QDialogButtonBox* pButtonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
      Qt::Horizontal, this);
   // Button Box End


   // Overall Layout Begin
   mpUseExistingFileRadio = new QRadioButton("Use Existing Gains/Offsets File");
   mpCalculateRadio = new QRadioButton("Calculate Gains/Offsets");

   QVBoxLayout* pOverallLayout = new QVBoxLayout(this);
   pOverallLayout->setMargin(10);
   pOverallLayout->setSpacing(5);
   pOverallLayout->addWidget(mpUseExistingFileRadio);
   pOverallLayout->addWidget(pUseExistingFileGroup);
   pOverallLayout->addWidget(mpCalculateRadio);
   pOverallLayout->addWidget(pCalculateGroup);
   pOverallLayout->addWidget(pButtonBox);
   // Overall Layout End


   // Make GUI connections
   VERIFYNRV(connect(mpUseExistingFileRadio, SIGNAL(toggled(bool)), pUseExistingFileGroup, SLOT(setEnabled(bool))));
   VERIFYNRV(connect(mpCalculateRadio, SIGNAL(toggled(bool)), pCalculateGroup, SLOT(setEnabled(bool))));
   VERIFYNRV(connect(mpElementComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentIndexChanged(int))));
   VERIFYNRV(connect(pNewElementButton, SIGNAL(clicked()), this, SLOT(newElement())));
   VERIFYNRV(connect(pDeleteElementButton, SIGNAL(clicked()), this, SLOT(deleteElement())));
   if (ElmCore::hasSettingElmHelp())
   {
      pButtonBox->addButton(QDialogButtonBox::Help);
      VERIFYNRV(connect(pButtonBox, SIGNAL(helpRequested()), this, SLOT(help())));
   }
   VERIFYNRV(connect(pButtonBox, SIGNAL(accepted()), this, SLOT(accept())));
   VERIFYNRV(connect(pButtonBox, SIGNAL(rejected()), this, SLOT(reject())));
   VERIFYNRV(connect(pDeletePixelButton, SIGNAL(clicked()), this, SLOT(deletePixels())));
   VERIFYNRV(connect(pSignatureButton, SIGNAL(clicked()), this, SLOT(selectSignature())));


   // AOI toolbar defaults
   Service<DesktopServices> pDesktopServices;
   pDesktopServices->setAoiSelectionTool(RECTANGLE_OBJECT, DRAW);


   // Create an initial element
   newElement();


   // Enable the appropriate GroupBox
   const QString defaultFilename = QString::fromStdString(mpElmInteractive->getDefaultGainsOffsetsFilename());
   if (QFile::exists(defaultFilename) == true)
   {
      mpUseExistingFileRadio->setChecked(true);
      mpExistingFileBrowser->setFilename(defaultFilename);
   }
   else
   {
      mpCalculateRadio->setChecked(true);
   }
}
Ejemplo n.º 5
0
void FFTConvolutionDlg::convolve() { 
    Service<ModelServices> pModel; VERIFYNRV(pModel.get() != NULL);
    Service<DesktopServices> pDesktop; VERIFYNRV(pDesktop.get() != NULL);
    Service<UtilityServices> pUtils; VERIFYNRV(pUtils.get() != NULL);

	mProgressTracker.report("Retrieving image to convolve", 1, NORMAL, true);
    Image imgToConvolve(widgetInputSelection->getImageToConvolveView());
    if (imgToConvolve.pView == NULL) { mProgressTracker.report("Error: Primary data set does not exist. Go back to the Dataset Select Page and select a new Primary Dataset.", 0, ERRORS); return; }

	mProgressTracker.report("Retrieving convolution kernel", 2, NORMAL, true);
    Image imgConvolutionKernel(widgetInputSelection->getConvolutionKernelView());
    if (imgConvolutionKernel.pView == NULL) { mProgressTracker.report("Error: Secondary data set does not exist. Go back to the Dataset Select Page and select a new Secondary Dataset.", 0, ERRORS); return; }

   // Convolved Image Result
mProgressTracker.report("Initializing output", 3, NORMAL, true);
   EncodingType resultType = imgToConvolve.pDataDescriptor->getDataType();
		  mProgressTracker.report((string("Result type ") + intToStr(resultType)).c_str(), 4, NORMAL, true);
   qDebug("resultType = %i", (int) resultType);
      /*if (resultType == INT4SCOMPLEX) { resultType = INT4SBYTES; }
      else if (resultType == FLT8COMPLEX) { resultType = FLT8BYTES; }*/

   qDebug("resultType = %i", (int) resultType);
//      INT1SBYTE = 0,  /**< char */
//      00208    INT1UBYTE = 1,      /**< unsigned char */
//      00209    INT2SBYTES = 2,     /**< short */
//      00210    INT2UBYTES = 3,     /**< unsigned short */
//      00211    INT4SCOMPLEX = 4,   /**< complex short */
//      00212    INT4SBYTES = 5,     /**< int */
//      00213    INT4UBYTES = 6,     /**< unsigned int */
//      00214    FLT4BYTES = 7,      /**< float */
//      00215    FLT8COMPLEX = 8,    /**< complex float */
//      00216    FLT8BYTES = 9       /**< double */

   std::string resultName = imgToConvolve.getName() + " conv " + imgConvolutionKernel.getName();

   ModelResource<RasterElement> pResult(RasterUtilities::createRasterElement(resultName,
         imgToConvolve.getRowCount(), imgToConvolve.getColumnCount(), imgToConvolve.getBandCount(),
         resultType, imgToConvolve.pDataDescriptor->getInterleaveFormat(),
         imgToConvolve.pDataDescriptor->getProcessingLocation() == IN_MEMORY));
      pResult->copyClassification(imgToConvolve.pRaster);
      pResult->getMetadata()->merge(imgToConvolve.pDataDescriptor->getMetadata()); //copy original metadata
      Image imgResult = Image(pResult.get());
      resultRasterElement = imgResult.pRaster;
      if (imgResult.pRaster == NULL) { mProgressTracker.report("Unable to create result data set.", 0, ERRORS, true); return; }

      if (Service<ApplicationServices>()->isBatch()) { return; }
      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(Service<DesktopServices>()->createWindow(resultRasterElement->getName(), SPATIAL_DATA_WINDOW));
      pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
//      pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL) {
         Service<DesktopServices>()->deleteWindow(pWindow);
         mProgressTracker.report("Unable to create view.", 0, ERRORS, true); return;
      }
      if (!pView->setPrimaryRasterElement(resultRasterElement)) qDebug("Failed to attach raster element");

      RasterLayer* pLayer = NULL; { UndoLock lock(pView); pLayer = static_cast<RasterLayer*>(pView->createLayer(RASTER, resultRasterElement)); }
      if (pLayer == NULL) {
   #pragma message(__FILE__ "(" STRING(__LINE__) ") : warning : This would be cleaner with a WindowResource. If one becomes available, use it instead. (tclarke)")
         Service<DesktopServices>()->deleteWindow(pWindow);
         mProgressTracker.report("Unable to create layer.", 0, ERRORS, true);
         return;
      }

      // Perform Convolution
   	mProgressTracker.report("Performing convolution", 5, NORMAL, true);
     unsigned int bandCount = imgToConvolve.pDataDescriptor->getBands().size();
//      qDebug("bandCount = %i", bandCount);
  //    qDebug("%i -- %i:%i:%i", (int) imgResult.pDataDescriptor->getDataType(), imgResult.getRowCount(), imgResult.getColumnCount(), imgResult.getBandCount());
      typedef unsigned char T;
//	  ProgressTracker ptBands = ProgressTracker(;
      for (unsigned int bandNum = 0; bandNum < bandCount; ++bandNum) {
		  mProgressTracker.report("Processing band", 5 + (99 - 5)*(bandNum/(double) bandCount), NORMAL, true);
          Opticks2DData<T> dataToConvolve(&imgToConvolve, bandNum);
          Opticks2DData<T> convolutionKernel(&imgConvolutionKernel, bandNum);
          Opticks2DData<T> result(&imgResult, bandNum, true);

          Convolution2D_FFT<T> convolution(&dataToConvolve, &convolutionKernel, &result);
          convolution.convolve();
	  }

   	mProgressTracker.report("Convolution complete", 99, NORMAL, true);

	pResult->updateData();
      pResult.release();
}
Ejemplo n.º 6
0
bool ShapeFileImporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   // prevent session auto save while importing shape file
   SessionSaveLock lock;

   StepResource pStep("Run Importer", "app", "F5264701-1D60-474b-AB62-C674A6AC1477");
   mpStep = pStep.get();
   pStep->addProperty("name", getName());

   mpProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   Progress* pProgress = mpProgress;

   // interactive

   SpatialDataView* pView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
   RasterElement* pRaster = NULL;

   FAIL_IF(pView == NULL, "Could not find view to insert into.", return false);

   AnnotationElement* pAnno = pInArgList->getPlugInArgValue<AnnotationElement>(Importer::ImportElementArg());
   FAIL_IF(pAnno == NULL, "Could not find created element.", return false);

   AnnotationLayer* pAnnotationLayer = NULL;
   const LayerList* pLayerList = pView->getLayerList();
   FAIL_IF(pLayerList == NULL, "Could not find layer list.", return false);

   pRaster = pLayerList->getPrimaryRasterElement();

   FAIL_IF(pRaster == NULL, "No data cube could be found.", return false);
   FAIL_IF(!pRaster->isGeoreferenced(), "No georeference could be found.", return false)

   const DataDescriptor* pDescriptor = pAnno->getDataDescriptor();
   FAIL_IF(pDescriptor == NULL, "The descriptor is invalid.", return false);

   createFeatureClassIfNeeded(pDescriptor);
   if (mpFeatureClass.get() == NULL)
   {
      // Progress and Step has been taken care of
      return false;
   }

   if (mpOptionsWidget != NULL)
   {
      mpOptionsWidget->applyChanges();
   }

   const ArcProxyLib::ConnectionParameters& connect = mpFeatureClass->getConnectionParameters();
   pStep->addProperty("connectionParameters", connect.toString());

   vector<ArcProxyLib::ConnectionType> availableConnections = getAvailableConnectionTypes();
   FAIL_IF(find(availableConnections.begin(), availableConnections.end(), 
      connect.getConnectionType()) == availableConnections.end(), 
      "The selected connection type is not available.", return false)

   Service<ModelServices> pModel;
   FAIL_IF(!pModel->setElementParent(pAnno, pRaster) || !pModel->setElementName(pAnno, connect.getFeatureClass()),
      "This shape file has already been imported", return false)

   FAIL_IF(pAnno->setGeocentric(true) == false, "Could not set the element to geocentric.", return false)

   UndoGroup group(pView, "Set Object Properties");

   string layerName = mpFeatureClass->getLayerName();

   pAnnotationLayer = static_cast<AnnotationLayer*>(pLayerList->getLayer(ANNOTATION, pAnno, layerName));
   if (pAnnotationLayer == NULL)
   {
      pAnnotationLayer = static_cast<AnnotationLayer*>(pView->createLayer(ANNOTATION, pAnno, layerName));
   }
   if (pAnnotationLayer != NULL && mpFeatureClass->hasLabels())
   {
      pAnnotationLayer->setShowLabels(true);
   }

   pAnnotationLayer->setLayerLocked(true);

   ModelResource<Any> pAny("Geographic feature", pAnno, "FeatureClass");

   mpFeatureClass->setParentElement(pAnno);

   if (!mpFeatureClass->open(mMessageText) || !mpFeatureClass->update(mpProgress, mMessageText))
   {
      if (mpProgress)
      {
         mpProgress->updateProgress("Error: " + mMessageText, 0, ERRORS);
      }

      pStep->finalize(Message::Failure, mMessageText);
      return false;
   }

   pAny->setData(mpFeatureClass.release());
   pAny.release();
   mpProgress->updateProgress("Complete", 100, NORMAL);
   pStep->finalize(Message::Success);

   return true;
}
Ejemplo n.º 7
0
    session->close( OK, "Hello, World!", { { "Content-Length", "32" } } );
}

SCENARIO( "custom resource failed filter validation handler", "[resource]" )
{
    GIVEN( "I publish a resource at '/resources/1' with a HTTP 'GET' method handler" )
    {
        auto resource = make_shared< Resource >( );
        resource->set_path( "/resources/1" );
        resource->set_method_handler( "GET", { { "Content-Type", "application/csv" } }, &get_method_handler );

        auto settings = make_shared< Settings >( );
        settings->set_port( 1984 );
        settings->set_default_header( "Connection", "close" );

        Service service;
        service.publish( resource );
        service.set_failed_filter_validation_handler( &failed_filter_validation_handler );

        thread service_thread( [ &service, settings ] ( )
        {
            service.start( settings );
        } );

        WHEN( "I perform a HTTP 'GET' request to '/resources/1' with header 'Content-Type: application/yaml'" )
        {
            Http::Request request;
            request.port = 1984;
            request.host = "localhost";
            request.path = "/resources/1";
            request.headers.insert( make_pair( "Content-Type", "application/yaml" ) );
Ejemplo n.º 8
0
bool DataMergeGui::mergeData() 
{
//	Service<ModelServices> pModel;
	StepResource pStep("Data Merge Begin", "app", "5E4BCD48-E662-408b-93AF-F9127CE56C66");	
	if (mergeList->count() == 0)
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "No RasterElement to merge", "OK");
		pStep->finalize(Message::Failure, "No RasterElement to merge");
		return false;
	}

//	pProgress = new Progress(this, "Progress Reporter");
//	std::vector<DataElement*> cubes = pModel->getElements("RasterElement");
/*	if (mergeElementList.size() == 0)
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "No RasterElement input found!", "OK");
		pStep->finalize(Message::Failure, "No RasterElement input found!");
		return false;
	} */
	//QListWidgetItem *tmpItem = mergeList->item(i0);
	//QString tmpItemText = tmpItem->text();
	RasterElement* pInitData = extractRasterElement(mergeList->item(0)->text());

//	vector<RasterElement*>::iterator initIter = mergeElementList.begin();
//	RasterElement* pInitData = model_cast<RasterElement*>(*initIter);

	if (pInitData == NULL)
	{
		pStep->finalize(Message::Failure, "Cube Data error!");
		QMessageBox::critical(this, "Error", "pInitData Error");
		return false;
	}

	RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pInitData->getDataDescriptor());
	EncodingType type = pDesc->getDataType();
	int rowCount = pDesc->getRowCount();
	int colCount = pDesc->getColumnCount();
	int bandCount = mergeList->count();

	RasterElement* pDesRaster = RasterUtilities::createRasterElement("DataMergeCube", rowCount,
      colCount, bandCount, type, BIP, true, NULL);
	
	if (pDesRaster == NULL)
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "Create RasterElement failed, Please close the previous merge result!", "OK");
		pStep->finalize(Message::Failure, "No RasterElement input found!");
		return false;
	}

	FactoryResource<DataRequest> pRequest;
	pRequest->setInterleaveFormat(BIP);
	DataAccessor pDesAcc = pDesRaster->getDataAccessor(pRequest.release());
	
	if (!pDesAcc.isValid())
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "pDesRaster Data Accessor Error!", "OK");
		pStep->finalize(Message::Failure, "pDesRaster Data Accessor Error!");
		return false;
	} 

	if (pProgress == NULL) 
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "pProgress Initialize Error!", "OK");
		pStep->finalize(Message::Failure, "pProgress Error!");
		return false;
	}
//	progressDialog = new QProgressDialog();
//	progressDialog->setRange(0, rowCount);
	
	//int index = 0;
	for (int i = 0; i < mergeList->count(); i++)
	{
		QListWidgetItem *tmpItem = mergeList->item(i);
		QString tmpItemText = tmpItem->text();
		RasterElement* pData = extractRasterElement(tmpItemText);
		int band = extractMergeBand(tmpItemText);

		if (pData != NULL)
		{
			RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pData->getDataDescriptor());
			if (rowCount != pDesc->getRowCount())
			{
				QMessageBox::critical(NULL, "Spectral Data Merge", "Merge Data Format Error!", "OK");
				pStep->finalize(Message::Failure, "Merge Data Row Format Error!");
				return false;			
			}
					
			if (colCount != pDesc->getColumnCount())
			{
				QMessageBox::critical(NULL, "Spectral Data Merge", "Merge Data Format Error!", "OK");
				pStep->finalize(Message::Failure, "Merge Data Column Format Error!");
				return false;			
			}
	//		QMessageBox::about(this, "Test", "Here2");
			FactoryResource<DataRequest> pRequest;
			pRequest->setInterleaveFormat(BIP);
		//	pRequest->setWritable(true);
			DataAccessor pSrcAcc = pData->getDataAccessor(pRequest.release());	
			switchOnEncoding(pDesc->getDataType(), mergeElement, NULL, rowCount, 
				colCount, pSrcAcc, pDesAcc, i, band, pProgress, mergeList->count());
	//		QMessageBox::about(this, "Test", "Here5");
		}
		else {
			QMessageBox::critical(this, "Error", "pData is NULL");
			return false;
		}

	//	mergeElementList.push_back(filenameMap[tmpItemText.toStdString()]);
	}

	Service<DesktopServices> pDesktop;
	SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow("DataMergeResult",
	   SPATIAL_DATA_WINDOW));

    SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
    if (pView == NULL)
    {
		pStep->finalize(Message::Failure, "SpatialDataView error!");
	    return false;
    }

	pView->setPrimaryRasterElement(pDesRaster);
    pView->createLayer(RASTER, pDesRaster);
	

	if (pDesc != NULL)
    {
		const RasterFileDescriptor* pFileDescriptor = dynamic_cast<const RasterFileDescriptor*>(pDesc->getFileDescriptor());
        if (pFileDescriptor != NULL)
        {
			Service<ModelServices> pModel;
            if (pModel.get() != NULL)
            {
				list<GcpPoint> gcps;             
                gcps = pFileDescriptor->getGcps();           
                if (gcps.empty() == true)
                {
					if (pInitData->isGeoreferenced())
                    {
						GcpPoint gcp;

                        // Lower left
                        gcp.mPixel.mX = 0.0;
                        gcp.mPixel.mY = 0.0;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);

                        // Lower right
                        gcp.mPixel.mX = colCount - 1;
                        gcp.mPixel.mY = 0.0;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);

                        // Upper left
                        gcp.mPixel.mX = 0.0;
                        gcp.mPixel.mY = rowCount - 1;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);

                        // Upper right
                        gcp.mPixel.mX = colCount - 1;
                        gcp.mPixel.mY = rowCount - 1;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);

                        // Center
                        gcp.mPixel.mX = colCount / 2.0;
                        gcp.mPixel.mY = rowCount / 2.0;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);
                     }
                  }

                  if (gcps.empty() == false)
                  {
                     DataDescriptor* pGcpDescriptor = pModel->createDataDescriptor("Corner Coordinates",
                        "GcpList", pDesRaster);
                     if (pGcpDescriptor != NULL)
                     {
                        GcpList* pGcpList = static_cast<GcpList*>(pModel->createElement(pGcpDescriptor));
                        if (pGcpList != NULL)
                        {
                           // Add the GCPs to the GCP list
                           pGcpList->addPoints(gcps);

                           // Create the GCP list layer
                           pView->createLayer(GCP_LAYER, pGcpList);
                        }
                     }
                  }
               }
		}
	}

	return true;
}
Ejemplo n.º 9
0
bool Scharr::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Scharr Edge Detection", "app", "576E21A3-BF43-424B-8FD3-061CAA392D49");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   if (pDesc->getDataType() == INT4SCOMPLEX || pDesc->getDataType() == FLT8COMPLEX)
   {
      std::string msg = "Edge detection cannot be performed on complex types.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }

   FactoryResource<DataRequest> pRequest;
   DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Edge_Detection_Result", pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType()));
   if (pResultCube.get() == NULL)
   {
      std::string msg = "A raster cube could not be created.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Calculating result", row * 100 / pDesc->getRowCount(), NORMAL);
      }
      if (isAborted())
      {
         std::string msg = getName() + " has been aborted.";
         pStep->finalize(Message::Abort, msg);
         if (pProgress != NULL)
         {
            pProgress->updateProgress(msg, 0, ABORT);
         }
         return false;
      }
      if (!pDestAcc.isValid())
      {
         std::string msg = "Unable to access the cube data.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }
      for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
         switchOnEncoding(pDesc->getDataType(), edgeDetection, pDestAcc->getColumn(), pSrcAcc, row, col,
            pDesc->getRowCount(), pDesc->getColumnCount());
         pDestAcc->nextColumn();
      }

      pDestAcc->nextRow();
   }

   if (!isBatch())
   {
      Service<DesktopServices> pDesktop;

      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));

      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         std::string msg = "Unable to create view.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }

      pView->setPrimaryRasterElement(pResultCube.get());
      pView->createLayer(RASTER, pResultCube.get());
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Edge Detection is complete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Scharr_Edge_Result", pResultCube.release());

   pStep->finalize();
   return true;
}
Ejemplo n.º 10
0
ClockDevice::ClockDevice() : Device(CLOCK_DESCRIPTION_FILE_NAME)
#else
ClockDevice::ClockDevice() : Device()
#endif
{
#if !defined(USE_CLOCK_DESCRIPTION_FILE)
	loadDescription(CLOCK_DEVICE_DESCRIPTION);
	Service *timeService = getService("urn:schemas-upnp-org:service:timer:1");
	timeService->loadSCPD(CLOCK_SERVICE_DESCRIPTION);
#endif

	Action *getTimeAction = getAction("GetTime");
	getTimeAction->setActionListener(this);
		
	Action *setTimeAction = getAction("SetTime");
	setTimeAction->setActionListener(this);
		
	ServiceList *serviceList = getServiceList();
	Service *service = serviceList->getService(0);
	service->setQueryListener(this);

	timeVar = getStateVariable("Time");

	setLeaseTime(60);
}

////////////////////////////////////////////////
// ActionListener
////////////////////////////////////////////////

bool ClockDevice::actionControlReceived(Action *action)
{
	const char *actionName = action->getName();
	if (strcmp("GetTime", actionName) == 0) {
		std::string dateStr;
		Clock clock;
		clock.toString(dateStr);
		Argument *timeArg = action->getArgument("CurrentTime");
		timeArg->setValue(dateStr.c_str());
		return true;
	}
	if (strcmp(actionName, "SetTime") == 0) {
		Argument *timeArg = action->getArgument("NewTime");
		const char *newTime = timeArg->getValue();
		Argument *resultArg = action->getArgument("Result");
		std::ostringstream valbuf;
		valbuf << "Not implemented (" << newTime << ")";
		resultArg->setValue(valbuf.str().c_str());
		return true;
	}
	return false;
}

////////////////////////////////////////////////
// QueryListener
////////////////////////////////////////////////

bool ClockDevice::queryControlReceived(StateVariable *stateVar)
{
	const char *varName = stateVar->getName();
	Clock clock;
	string clockVal;
	stateVar->setValue(clock.toString(clockVal));
	return true;
}

////////////////////////////////////////////////
// HttpRequestListner
////////////////////////////////////////////////
	
uHTTP::HTTP::StatusCode ClockDevice::httpRequestRecieved(HTTPRequest *httpReq)
{
	ParameterList paramList;
	httpReq->getParameterList(paramList);
	for (int n=0; n<paramList.size(); n++) {
		Parameter *param = paramList.getParameter(n);
		cout << "[" << n << "] : " << param->getName() << " = " << param->getValue() << endl;
	}

	string uri;
	httpReq->getURI(uri);
	if (uri.find(CLOCK_PRESENTATION_URI) == string::npos)  {
		return Device::httpRequestRecieved(httpReq);
	}
			 
	string clockStr;
	Clock clock;
	clock.toString(clockStr);
	string contents;
	contents = "<HTML><BODY><H1>";
	contents += clockStr;
	contents += "</H1></BODY></HTML>";
		
	HTTPResponse httpRes;
	httpRes.setStatusCode(HTTP::OK_REQUEST);
	httpRes.setContent(contents);
	return httpReq->post(&httpRes);
}
Ejemplo n.º 11
0
    return;
}

void authentication_handler( const shared_ptr< Session >, const function< void ( const shared_ptr< Session > ) >& )
{
    return;
}

SCENARIO( "runtime service modifications", "[service]" )
{
    auto settings = make_shared< Settings >( );
    settings->set_port( 1984 );

    shared_ptr< thread > worker = nullptr;

    Service service;
    service.set_ready_handler( [ &worker ]( Service & service )
    {
        worker = make_shared< thread >( [ &service ] ( )
        {
            GIVEN( "I publish a resource at '/resources/1' with a HTTP 'GET' method handler" )
            {
                WHEN( "I attempt to modify service settings" )
                {
                    auto resource = make_shared< Resource >( );
                    resource->set_path( "/acceptance-tests/runtime service modifications" );

                    THEN( "I should see an runtime error of 'Runtime modifications of the service are prohibited.'" )
                    {
                        REQUIRE_THROWS_AS( service.publish( resource ), runtime_error );
                        REQUIRE_THROWS_AS( service.suppress( resource ), runtime_error );
Ejemplo n.º 12
0
int Service::connect_producer( Service &producer, int index )
{
	return mlt_service_connect_producer( get_service( ), producer.get_service( ), index );
}
Ejemplo n.º 13
0
Service::Service( Service &service ) :
	Properties( false ),
	instance( service.get_service( ) )
{
	inc_ref( );
}
bool ImageRegistration::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Image Registration", "app", "A2E0FC44-2A31-41EE-90F8-805773D01FCA");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   //RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());

   std::vector<Window*> windows;
   Service<DesktopServices>()->getWindows(SPATIAL_DATA_WINDOW, windows);
   std::vector<RasterElement*> elements;
   for (unsigned int i = 0; i < windows.size(); ++i)
   {
       SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(windows[i]);
       if (pWindow == NULL)
       {
           continue;
       }
       LayerList* pList = pWindow->getSpatialDataView()->getLayerList();
       elements.push_back(pList->getPrimaryRasterElement());
   }

   RasterElement* pCube = elements[0];
   RasterElement* pCubeRef = elements[1];
   if ((pCube == NULL) || (pCubeRef == NULL))
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   
   EncodingType ResultType = pDesc->getDataType();
   if (pDesc->getDataType() == INT4SCOMPLEX)
   {
      ResultType = INT4SBYTES;
   }
   else if (pDesc->getDataType() == FLT8COMPLEX)
   {
      ResultType = FLT8BYTES;
   }

   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BSQ);
   DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release());

   FactoryResource<DataRequest> pRequestRef;
   pRequestRef->setInterleaveFormat(BSQ);
   DataAccessor pSrcAccRef = pCubeRef->getDataAccessor(pRequestRef.release());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Image_Registration_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType));
   if (pResultCube.get() == NULL)
   {
      std::string msg = "A raster cube could not be created.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }

   std::vector<int> badValues = pDesc->getBadValues();
   //badValues.push_back(0);
   RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(pResultCube->getDataDescriptor());
   Statistics* pStatistics = pResultCube->getStatistics(pDescriptor->getActiveBand(0));
   pStatistics->setBadValues(badValues);

   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());
   
   nCountMas = 0;
   nCountRef = 0;
   int windowSize = 6;
   double *pBuffer = (double *)calloc(pDesc->getRowCount()*pDesc->getColumnCount(), sizeof(double));

   GetGrayScale(pDesc->getDataType());

   
   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
	   if (pProgress != NULL)
       {
           pProgress->updateProgress("Image registration", row * 100 / pDesc->getRowCount(), NORMAL);
       }
       if (isAborted())
       {
          std::string msg = getName() + " has been aborted.";
          pStep->finalize(Message::Abort, msg);
          if (pProgress != NULL)
          {
             pProgress->updateProgress(msg, 0, ABORT);
          }
          return false;
       }
       for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
       {
	       locateAllStarPosition(pSrcAcc, pSrcAccRef, row, col, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), windowSize, pBuffer);
       }
   }

   ModifyCenter(pSrcAcc, pDesc->getDataType(), windowSize, nCountMas, nStarPositionsMas);
   ModifyCenter(pSrcAccRef, pDesc->getDataType(), windowSize, nCountRef, nStarPositionsRef);

   GetAllNeighborStars();
   GetMatchingStars();
   
   GetParameters(pDesc->getRowCount(), pDesc->getColumnCount());
  
   DrawStars(pBuffer, pSrcAccRef, pDesc->getDataType(), matrixT, pDesc->getRowCount(), pDesc->getColumnCount());

   //Output the value 
      for (unsigned int m = 0; m < pDesc->getRowCount(); m++)
      {
	      for (unsigned int n = 0; n < pDesc->getColumnCount(); n++)
	      {
		      if (isAborted())
              {
                  std::string msg = getName() + " has been aborted.";
                  pStep->finalize(Message::Abort, msg);
                  if (pProgress != NULL)
                  {
                      pProgress->updateProgress(msg, 0, ABORT);
                  }
                  return false;
              }
				      
			  if (!pDestAcc.isValid())
              {
                  std::string msg = "Unable to access the cube data.";
                  pStep->finalize(Message::Failure, msg);
                  if (pProgress != NULL) 
                  {
                      pProgress->updateProgress(msg, 0, ERRORS);
                   }
                   return false;
               }

				       
			  switchOnEncoding(ResultType, updatePixel, pDestAcc->getColumn(), pBuffer, m, n, pDesc->getRowCount(), pDesc->getColumnCount());       
			  pDestAcc->nextColumn();
				   
		  }
				   
		  pDestAcc->nextRow();
		  
	  }
   free(pBuffer);
   


   if (!isBatch())
   {
      Service<DesktopServices> pDesktop;

      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));

      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         std::string msg = "Unable to create view.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }

      pView->setPrimaryRasterElement(pResultCube.get());
      pView->createLayer(RASTER, pResultCube.get());
   }

   double theta = std::acos(matrixT[0][0])*180.0/3.1415926;

   std::string msg = "Image Registration is complete.\n Translation x = " +  StringUtilities::toDisplayString(round(shiftX)) + ", y = " + 
	                 StringUtilities::toDisplayString(round(shiftY)) + ", rotation = " + StringUtilities::toDisplayString(round(theta)) + " degree";
   if (pProgress != NULL)
   {
	   
       pProgress->updateProgress(msg, 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Image Registration Result", pResultCube.release());

   pStep->finalize();


   return true;
}
Ejemplo n.º 15
0
int
main(int ac, const char* av[])
{

// get command line options
xmreg::CmdLineOptions opts {ac, av};

auto help_opt         = opts.get_option<bool>("help");

// if help was chosen, display help text and finish
if (*help_opt)
{
    return EXIT_SUCCESS;
}

auto do_not_relay_opt = opts.get_option<bool>("do-not-relay");
auto testnet_opt      = opts.get_option<bool>("testnet");
auto port_opt         = opts.get_option<string>("port");
auto config_file_opt  = opts.get_option<string>("config-file");


bool testnet          = *testnet_opt;
bool do_not_relay     = *do_not_relay_opt;


// check if config-file provided exist
if (!boost::filesystem::exists(*config_file_opt))
{
    cerr << "Config file " << *config_file_opt
         << " does not exist" << endl;
    return EXIT_FAILURE;
}

nlohmann::json config_json;

try
{
    // try reading and parsing json config file provided
    std::ifstream i(*config_file_opt);
    i >> config_json;
}
catch (const std::exception& e)
{
    cerr << "Error reading confing file "
         << *config_file_opt << ": "
         << e.what() << endl;
    return EXIT_FAILURE;
}


//cast port number in string to uint16
uint16_t app_port   = boost::lexical_cast<uint16_t>(*port_opt);

// get blockchain path
// if confing.json paths are emtpy, defeault monero
// paths are going to be used
path blockchain_path = testnet
                       ? path(config_json["blockchain-path"]["testnet"].get<string>())
                       : path(config_json["blockchain-path"]["mainnet"].get<string>());


if (!xmreg::get_blockchain_path(blockchain_path, testnet))
{
    cerr << "Error getting blockchain path." << endl;
    return EXIT_FAILURE;
}

cout << "Blockchain path: " << blockchain_path.string() << endl;



string deamon_url = testnet
                    ? config_json["daemon-url"]["testnet"]
                    : config_json["daemon-url"]["mainnet"];

// set mysql/mariadb connection details
xmreg::MySqlConnector::url      = config_json["database"]["url"];
xmreg::MySqlConnector::username = config_json["database"]["user"];
xmreg::MySqlConnector::password = config_json["database"]["password"];
xmreg::MySqlConnector::dbname   = config_json["database"]["dbname"];

// set blockchain status monitoring thread parameters
xmreg::CurrentBlockchainStatus::blockchain_path
        =  blockchain_path.string();
xmreg::CurrentBlockchainStatus::testnet
        = testnet;
xmreg::CurrentBlockchainStatus::do_not_relay
        = do_not_relay;
xmreg::CurrentBlockchainStatus::deamon_url
        = deamon_url;
xmreg::CurrentBlockchainStatus::refresh_block_status_every_seconds
        = config_json["refresh_block_status_every_seconds"];
xmreg::CurrentBlockchainStatus::max_number_of_blocks_to_import
        = config_json["max_number_of_blocks_to_import"];
xmreg::CurrentBlockchainStatus::search_thread_life_in_seconds
        = config_json["search_thread_life_in_seconds"];
xmreg::CurrentBlockchainStatus::import_fee
        = config_json["wallet_import"]["fee"];

if (testnet)
{
    xmreg::CurrentBlockchainStatus::import_payment_address_str
            = config_json["wallet_import"]["testnet"]["address"];
    xmreg::CurrentBlockchainStatus::import_payment_viewkey_str
            = config_json["wallet_import"]["testnet"]["viewkey"];
}
else
{
    xmreg::CurrentBlockchainStatus::import_payment_address_str
            = config_json["wallet_import"]["mainnet"]["address"];
    xmreg::CurrentBlockchainStatus::import_payment_viewkey_str
            = config_json["wallet_import"]["mainnet"]["viewkey"];
}


// since CurrentBlockchainStatus class monitors current status
// of the blockchain (e.g., current height), its seems logical to
// make static objects for accessing the blockchain in this class.
// this way monero accessing blockchain variables (i.e. mcore and core_storage)
// are not passed around like crazy everywhere. Uri( "file:///tmp/dh2048.pem"
// There are here, and this is the only class that
// has direct access to blockchain and talks (using rpc calls)
// with the deamon.
if (!xmreg::CurrentBlockchainStatus::init_monero_blockchain())
{
    cerr << "Error accessing blockchain." << endl;
    return EXIT_FAILURE;
}

// launch the status monitoring thread so that it keeps track of blockchain
// info, e.g., current height. Information from this thread is used
// by tx searching threads that are launched for each user independently,
// when they log back or create new account.
xmreg::CurrentBlockchainStatus::start_monitor_blockchain_thread();


// create REST JSON API services

xmreg::YourMoneroRequests open_monero(
        shared_ptr<xmreg::MySqlAccounts>(new xmreg::MySqlAccounts{}));

// create Open Monero APIs
MAKE_RESOURCE(login);
MAKE_RESOURCE(get_address_txs);
MAKE_RESOURCE(get_address_info);
MAKE_RESOURCE(get_unspent_outs);
MAKE_RESOURCE(get_random_outs);
MAKE_RESOURCE(submit_raw_tx);
MAKE_RESOURCE(import_wallet_request);
MAKE_RESOURCE(import_recent_wallet_request);
MAKE_RESOURCE(get_tx);
MAKE_RESOURCE(get_version);

// restbed service
Service service;

// Publish the Open Monero API created so that front end can use it
service.publish(login);
service.publish(get_address_txs);
service.publish(get_address_info);
service.publish(get_unspent_outs);
service.publish(get_random_outs);
service.publish(submit_raw_tx);
service.publish(import_wallet_request);
service.publish(import_recent_wallet_request);
service.publish(get_tx);
service.publish(get_version);

auto settings = make_shared<Settings>( );

if (config_json["ssl"]["enable"])
{
    // based on the example provided at
    // https://github.com/Corvusoft/restbed/blob/34187502642144ab9f749ab40f5cdbd8cb17a54a/example/https_service/source/example.cpp
    auto ssl_settings = make_shared<SSLSettings>( );

    Uri ssl_key = Uri(config_json["ssl"]["ssl-key"].get<string>());
    Uri ssl_crt = Uri(config_json["ssl"]["ssl-crt"].get<string>());
    Uri dh_pem  = Uri(config_json["ssl"]["dh-pem"].get<string>());

    ssl_settings->set_http_disabled(true);
    ssl_settings->set_port(app_port);
    ssl_settings->set_private_key(ssl_key);
    ssl_settings->set_certificate(ssl_crt);
    ssl_settings->set_temporary_diffie_hellman(dh_pem);

    settings->set_ssl_settings(ssl_settings);

    // can check using: curl -k -v -w'\n' -X POST 'https://127.0.0.1:1984/get_version'

    cout << "Start the service at https://127.0.0.1:" << app_port << endl;
}
else
{
    settings->set_port(app_port);
    settings->set_default_header( "Connection", "close" );

    cout << "Start the service at http://127.0.0.1:" << app_port  << endl;
}


service.start(settings);

return EXIT_SUCCESS;
}