Example #1
0
File: Driver.cpp Project: mw2q/dbt5
// RunTest
void CDriver::runTest(int iSleep, int iTestDuration)
{
	g_tid = (pthread_t*) malloc(sizeof(pthread_t) * iUsers);

	// before starting the test run Trade-Cleanup transaction
	cout << endl <<
			"Running Trade-Cleanup transaction before starting the test..." <<
			endl;
	m_pCDM->DoCleanupTxn();
	cout << "Trade-Cleanup transaction completed." << endl << endl;

	// time to sleep between thread creation, convert from millaseconds to
	// nanoseconds.
	struct timespec ts, rem;
	ts.tv_sec = (time_t) (iSleep / 1000);
	ts.tv_nsec = (long) (iSleep % 1000) * 1000000;

	// Caulculate when the test should stop.
	int threads_start_time =
			(int) ((double) iSleep / 1000.0 * (double) iUsers);
	stop_time = time(NULL) + iTestDuration + threads_start_time;

	CDateTime dtAux;
	dtAux.SetToCurrent();

	cout << "Test is starting at " << dtAux.ToStr(02) << endl <<
			"Estimated duration of ramp-up: " << threads_start_time <<
			" seconds" << endl;

	dtAux.AddMinutes((iTestDuration + threads_start_time)/60);
	cout << "Estimated end time " << dtAux.ToStr(02) << endl;

	logErrorMessage(">> Start of ramp-up.\n");

	// start thread that runs the Data Maintenance transaction
	entryDMWorkerThread(this);

	// parameter for the new thread
	PCustomerThreadParam pThrParam;

	for (int i = 1; i <= iUsers; i++) {
		pThrParam = new TCustomerThreadParam;
		// zero the structure
		memset(pThrParam, 0, sizeof(TCustomerThreadParam));
		pThrParam->pDriver = this;

		entryCustomerWorkerThread(reinterpret_cast<void *>(pThrParam), i);

		// Sleep for between starting terminals
		while (nanosleep(&ts, &rem) == -1) {
			if (errno == EINTR) {
				memcpy(&ts, &rem, sizeof(timespec));
			} else {
				ostringstream osErr;
				osErr << "sleep time invalid " << ts.tv_sec << " s " <<
						ts.tv_nsec << " ns" << endl;
				logErrorMessage(osErr.str());
				break;
			}
		}
	}

	// mark end of ramp-up
	m_MixLock.lock();
	m_fMix << (int) time(NULL) << ",START,,," <<
			(long long) pthread_self() << endl;
	m_MixLock.unlock();

	logErrorMessage(">> End of ramp-up.\n\n");

	// wait until all threads quit
	// 0 represents the Data-Maintenance thread
	for (int i = 0; i <= iUsers; i++) {
		if (pthread_join(g_tid[i], NULL) != 0) {
			throw new CThreadErr( CThreadErr::ERR_THREAD_JOIN,
					"Driver::RunTest" );
		}
	}
}
KEquityPriceUpdateDlg::KEquityPriceUpdateDlg(QWidget *parent, const QString& securityId) :
    KEquityPriceUpdateDlgDecl(parent),
    m_fUpdateAll(false)
{
  QStringList headerList;
  headerList << i18n("Symbol") << i18nc("Equity name", "Name")
  << i18n("Price") << i18n("Date");

  lvEquityList->header()->setSortIndicator(0, Qt::AscendingOrder);
  lvEquityList->setColumnWidth(NAME_COL, 125);

  // This is a "get it up and running" hack.  Will replace this in the future.
  headerList << i18nc("Internal identifier", "ID")
  << i18nc("Online quote source", "Source");
  lvEquityList->setColumnWidth(ID_COL, 0);

  lvEquityList->setHeaderLabels(headerList);

  lvEquityList->setSelectionMode(QAbstractItemView::MultiSelection);
  lvEquityList->setAllColumnsShowFocus(true);

  btnUpdateAll->setEnabled(false);

  btnOK->setGuiItem(KStandardGuiItem::ok());
  btnCancel->setGuiItem(KStandardGuiItem::cancel());

  MyMoneyFile* file = MyMoneyFile::instance();

  //
  // Add each price pair that we know about
  //

  // send in securityId == "XXX YYY" to get a single-shot update for XXX to YYY.
  // for consistency reasons, this accepts the same delimiters as WebPriceQuote::launch()
  QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
  MyMoneySecurityPair currencyIds;
  if (splitrx.indexIn(securityId) != -1) {
    currencyIds = MyMoneySecurityPair(splitrx.cap(1).toUtf8(), splitrx.cap(2).toUtf8());
  }

  MyMoneyPriceList prices = file->priceList();
  for (MyMoneyPriceList::ConstIterator it_price = prices.constBegin(); it_price != prices.constEnd(); ++it_price) {
    const MyMoneySecurityPair& pair = it_price.key();
    if (file->security(pair.first).isCurrency() && (securityId.isEmpty() || (pair == currencyIds))) {
      const MyMoneyPriceEntries& entries = (*it_price);
      if (entries.count() > 0 && entries.begin().key() <= QDate::currentDate()) {
        addPricePair(pair);
        btnUpdateAll->setEnabled(true);
      }
    }
  }

  //
  // Add each investment
  //

  QList<MyMoneySecurity> securities = file->securityList();
  for (QList<MyMoneySecurity>::const_iterator it = securities.constBegin(); it != securities.constEnd(); ++it) {
    if (!(*it).isCurrency()
        && (securityId.isEmpty() || ((*it).id() == securityId))
        && !(*it).value("kmm-online-source").isEmpty()
       ) {
      addInvestment(*it);
      btnUpdateAll->setEnabled(true);
    }
  }

  // if list is empty, add the request price pair
  if (lvEquityList->invisibleRootItem()->childCount() == 0) {
    addPricePair(currencyIds, true);
  }

  connect(btnOK, SIGNAL(clicked()), this, SLOT(accept()));
  connect(btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
  connect(btnUpdateSelected, SIGNAL(clicked()), this, SLOT(slotUpdateSelectedClicked()));
  connect(btnUpdateAll, SIGNAL(clicked()), this, SLOT(slotUpdateAllClicked()));

  connect(&m_webQuote, SIGNAL(quote(QString,QString,QDate,double)),
          this, SLOT(slotReceivedQuote(QString,QString,QDate,double)));
  connect(&m_webQuote, SIGNAL(failed(QString,QString)),
          this, SLOT(slotQuoteFailed(QString,QString)));
  connect(&m_webQuote, SIGNAL(status(QString)),
          this, SLOT(logStatusMessage(QString)));
  connect(&m_webQuote, SIGNAL(error(QString)),
          this, SLOT(logErrorMessage(QString)));

  connect(lvEquityList, SIGNAL(itemSelectionChanged()), this, SLOT(slotUpdateSelection()));

  // Not implemented yet.
  btnConfigure->hide();
  //connect(btnConfigure, SIGNAL(clicked()), this, SLOT(slotConfigureClicked()));

  if (!securityId.isEmpty()) {
    btnUpdateSelected->hide();
    btnUpdateAll->hide();
    // delete layout1;

    QTimer::singleShot(100, this, SLOT(slotUpdateAllClicked()));
  }

  // Hide OK button until we have received the first update
  btnOK->setEnabled(false);

  slotUpdateSelection();

  // previous versions of this dialog allowed to store a "Don't ask again" switch.
  // Since we don't support it anymore, we just get rid of it
  KSharedConfigPtr config = KGlobal::config();
  KConfigGroup grp = config->group("Notification Messages");
  grp.deleteEntry("KEquityPriceUpdateDlg::slotQuoteFailed::Price Update Failed");
}
Example #3
0
bool GuiManager::isValidShipFile(const char *srcFilename,
                                 BerryBotsEngine *engine) {
  // TODO: Is this too slow? Should we keep this list in the cache so we don't
  //       have to do this on every startup / refresh - at least for packaged
  //       ships? In fact, just the presence in the cache could be considered
  //       a sign of validity.
  // TODO: Move this out of the GUI code.
  if (fileManager_->isLuaFilename(srcFilename)
      || fileManager_->isZipFilename(srcFilename)) {
    char *shipDir = 0;
    char *shipFilename = 0;
    try {
      fileManager_->loadShipFileData(getShipsDir().c_str(), srcFilename,
                                     &shipDir, &shipFilename,
                                     getCacheDir().c_str());
    } catch (FileNotFoundException *fnfe) {
      // Only possible if user deletes file from disk after we find it on disk
      // but before we validate it. Seems safe to fail silently.
      if (shipDir != 0) {
        delete shipDir;
      }
      if (shipFilename != 0) {
        delete shipFilename;
      }
      delete fnfe;
      return false;
    } catch (ZipperException *ze) {
      if (shipDir != 0) {
        delete shipDir;
      }
      if (shipFilename != 0) {
        delete shipFilename;
      }
      errorConsole_->print(srcFilename);
      errorConsole_->print(": ");
      errorConsole_->println(ze->what());
      wxMessageDialog errorMessage(NULL, ze->what(), "Unzip failure",
                                   wxOK | wxICON_EXCLAMATION);
      errorMessage.ShowModal();
      delete ze;
      return false;
    } catch (PackagedSymlinkException *pse) {
      if (shipDir != 0) {
        delete shipDir;
      }
      if (shipFilename != 0) {
        delete shipFilename;
      }
      errorConsole_->print(srcFilename);
      errorConsole_->print(": ");
      errorConsole_->println(pse->what());
      delete pse;
      return false;
    }
    lua_State *shipState;
    initShipState(&shipState, shipDir);

    if (luaL_loadfile(shipState, shipFilename)
        || engine->callUserLuaCode(shipState, 0, "", PCALL_VALIDATE)) {
      logErrorMessage(shipState, "Problem loading ship: %s");
      lua_close(shipState);
      delete shipDir;
      delete shipFilename;
      return false;
    }

    lua_getglobal(shipState, "configure");
    lua_getglobal(shipState, "init");
    if (lua_isnil(shipState, -1) || !lua_isnil(shipState, -2)) {
      lua_close(shipState);
      delete shipDir;
      delete shipFilename;
      return false;
    }
    
    lua_close(shipState);
    delete shipDir;
    delete shipFilename;
    return true;
  }
  return false;
}
void KEquityPriceUpdateDlg::slotReceivedQuote(const QString& _id, const QString& _symbol, const QDate& _date, const double& _price)
{
  QList<QTreeWidgetItem*> foundItems = lvEquityList->findItems(_id, Qt::MatchExactly, ID_COL);
  QTreeWidgetItem* item = 0;

  if (! foundItems.empty())
    item = foundItems.at(0);

  QTreeWidgetItem* next = 0;

  if (item) {
    if (_price > 0.0f && _date.isValid()) {
      QDate date = _date;
      if (date > QDate::currentDate())
        date = QDate::currentDate();

      double price = _price;
      QString id = _id.toUtf8();
      MyMoneySecurity sec;
      if (_id.contains(" ") == 0) {
        MyMoneySecurity security = MyMoneyFile::instance()->security(id);
        QString factor = security.value("kmm-online-factor");
        if (!factor.isEmpty()) {
          price *= MyMoneyMoney(factor).toDouble();
        }
        try {
          sec = MyMoneyFile::instance()->security(id);
          sec = MyMoneyFile::instance()->security(sec.tradingCurrency());
        } catch (const MyMoneyException &) {
          sec = MyMoneySecurity();
        }

      } else {
        QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
        if (splitrx.indexIn(_id) != -1) {
          try {
            sec = MyMoneyFile::instance()->security(splitrx.cap(2).toUtf8());
          } catch (const MyMoneyException &) {
            sec = MyMoneySecurity();
          }
        }
      }
      item->setText(PRICE_COL, KGlobal::locale()->formatMoney(price, sec.tradingSymbol(), KMyMoneyGlobalSettings::pricePrecision()));
      item->setText(DATE_COL, date.toString(Qt::ISODate));
      logStatusMessage(i18n("Price for %1 updated (id %2)", _symbol, _id));
      // make sure to make OK button available
      btnOK->setEnabled(true);
    } else {
      logErrorMessage(i18n("Received an invalid price for %1, unable to update.", _symbol));
    }

    prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
    item->setSelected(false);

    // launch the NEXT one ... in case of m_fUpdateAll == false, we
    // need to parse the list to find the next selected one
    next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(item) + 1);
    if (!m_fUpdateAll) {
      while (next && !next->isSelected()) {
        prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
        next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(next) + 1);
      }
    }
  } else {
    logErrorMessage(i18n("Received a price for %1 (id %2), but this symbol is not on the list. Aborting entire update.", _symbol, _id));
  }

  if (next) {
    m_webQuote.launch(next->text(SYMBOL_COL), next->text(ID_COL), next->text(SOURCE_COL));
  } else {
    finishUpdate();
  }
}
PassRefPtr<DatabaseBackendBase> DatabaseManager::openDatabaseBackend(ScriptExecutionContext* context,
    DatabaseType type, const String& name, const String& expectedVersion, const String& displayName,
    unsigned long estimatedSize, bool setVersionInNewDatabase, DatabaseError& error, String& errorMessage)
{
    ASSERT(error == DatabaseError::None);

    RefPtr<DatabaseContext> databaseContext = databaseContextFor(context);
    RefPtr<DatabaseBackendContext> backendContext = databaseContext->backend();

    RefPtr<DatabaseBackendBase> backend = m_server->openDatabase(backendContext, type, name, expectedVersion,
        displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage);

    if (!backend) {
        ASSERT(error != DatabaseError::None);

        switch (error) {
        case DatabaseError::DatabaseIsBeingDeleted:
        case DatabaseError::DatabaseSizeOverflowed:
        case DatabaseError::GenericSecurityError:
            logOpenDatabaseError(context, name);
            return 0;

        case DatabaseError::InvalidDatabaseState:
            logErrorMessage(context, errorMessage);
            return 0;

        case DatabaseError::DatabaseSizeExceededQuota:
            // Notify the client that we've exceeded the database quota.
            // The client may want to increase the quota, and we'll give it
            // one more try after if that is the case.
            {
                ProposedDatabase proposedDb(*this, context->securityOrigin(), name, displayName, estimatedSize);
                databaseContext->databaseExceededQuota(name,
                    DatabaseDetails(name.isolatedCopy(), displayName.isolatedCopy(), estimatedSize, 0));
            }
            error = DatabaseError::None;

            backend = m_server->openDatabase(backendContext, type, name, expectedVersion,
                displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage,
                AbstractDatabaseServer::RetryOpenDatabase);
            break;

        default:
            ASSERT_NOT_REACHED();
        }

        if (!backend) {
            ASSERT(error != DatabaseError::None);

            if (error == DatabaseError::InvalidDatabaseState) {
                logErrorMessage(context, errorMessage);
                return 0;
            }

            logOpenDatabaseError(context, name);
            return 0;
        }
    }

    return backend.release();
}