예제 #1
0
void login2Options::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("databaseURL", &valid);
  if (valid)
  {
    _databaseURL = param.toString();

    QString protocol;
    QString server;
    QString database;
    QString port;
    parseDatabaseURL(_databaseURL, protocol, server, database, port);
    _server->setText(server);
    _database->setText(database);
    _port->setText(port);
  }
  
  if(pParams.inList("useEnhancedAuthentication"))
    _enhancedAuth->setChecked(TRUE);

  if(pParams.inList("requireSSL"))
    _requireSSL->setChecked(TRUE);

  if (pParams.inList("dontSaveSettings"))
    _saveSettings = false;
}
예제 #2
0
void ReportWriterWindow::setCaption() {
    QString caption = QString("%1 %2 %3")
                          .arg(_name)
                          .arg(tr("Version"))
                          .arg(_version);

    QSqlDatabase * db = QSqlDatabase::database(QSqlDatabase::defaultConnection, false);
    if(db) {
        XSqlQuery dbname( "SELECT metric_value, CURRENT_USER AS username "
                          "FROM metric "
                          "WHERE (metric_name='DatabaseName')" );

        if ((dbname.isActive()) && (dbname.size())) {
            QString protocol;
            QString server;
            QString database;
            QString port;

            dbname.next();

            parseDatabaseURL((const QString &)_databaseURL, protocol, server, database, port);

            caption = QString( tr("%1 - %2 on %3/%4 AS %5") )
                            .arg(caption)
                            .arg(dbname.value("metric_value").toString())
                            .arg(server)
                            .arg(database)
                            .arg(dbname.value("username").toString());
        }
    }

    QMainWindow::setCaption(caption);
}
예제 #3
0
databaseInformation::databaseInformation(QWidget* parent, const char* name, bool modal, Qt::WFlags fl)
    : XDialog(parent, name, modal, fl)
{
    setupUi(this);

    // signals and slots connections
    connect(_save, SIGNAL(clicked()), this, SLOT(sSave()));

    QString server;
    QString database;
    QString port;

    _description->setFocus();

    _description->setText(_metrics->value("DatabaseName"));
    _comments->setText(_metrics->value("DatabaseComments"));
    _version->setText(_metrics->value("ServerVersion"));
    _patch->setText(_metrics->value("ServerPatchVersion"));
    _disallowMismatchClient->setChecked(_metrics->boolean("DisallowMismatchClientVersion"));

    QString access = _metrics->value("AllowedUserLogins");
    if("AdminOnly" == access)
        _access->setCurrentIndex(1);
    else if("Any" == access)
        _access->setCurrentIndex(2);
    else
        _access->setCurrentIndex(0);

    int val = _metrics->value("updateTickInterval").toInt();
    if(val < 1) val = 1;
    _interval->setValue(val);

    QString protocol;
    parseDatabaseURL(omfgThis->databaseURL(), protocol, server, database, port);
    _application->setText(_metrics->value("Application"));
    _server->setText(server);
    _name->setText(database);

    _disableAutoComplete->setChecked(_metrics->boolean("DisableAutoComplete"));

    q.exec( "SELECT numOfDatabaseUsers() AS databaseusers,"
            "       numOfServerUsers() AS serverusers;" );
    if (q.first())
    {
        _numOfDatabaseUsers->setText(q.value("databaseusers").toString());
        _numOfServerUsers->setText(q.value("serverusers").toString());
    }
//  ToDo

    if (!_privileges->check("ConfigDatabaseInfo"))
    {
        _description->setEnabled(FALSE);
        _comments->setEnabled(FALSE);
        _close->setText(tr("&Close"));
        _save->hide();
    }
}
예제 #4
0
void login2::populateDatabaseInfo()
{
  QString protocol;
  QString hostName;
  QString dbName;
  QString port;

  parseDatabaseURL(_databaseURL, protocol, hostName, dbName, port);
  _server->setText(hostName);
  _database->setText(dbName);
}
예제 #5
0
void login2::updateRecentOptionsActions()
{ 
  QMenu * recentMenu = new QMenu;
  QStringList list = xtsettingsValue("/xTuple/_recentOptionsList").toStringList();
  if (list.size())
  {
    list.takeFirst();
    int size = list.size();
    if (size > 5)
      size = 5;

    QString protocol;
    QString hostName;
    QString dbName;
    QString port;
    int alreadyExists;
  
    if (size)
    {
      //if (_otherOption->isChecked())
      _recent->setEnabled(true);
      QAction *act;
      for (int i = 0; i < size; ++i) 
      {
        act = new QAction(list.value(i).remove("psql://"),this);
        connect(act, SIGNAL(triggered()), this, SLOT(selectRecentOptions()));
        recentMenu->addAction(act);
        parseDatabaseURL(list.value(i), protocol, hostName, dbName, port);
        alreadyExists = _database->findText(dbName);
        if (alreadyExists == -1)
          _database->addItem(dbName);
      }
  
      recentMenu->addSeparator();

      act = new QAction(tr("Clear &Menu"), this);
      act->setObjectName(QLatin1String("__xt_action_clear_menu_"));
      connect(act, SIGNAL(triggered()), this, SLOT(clearRecentOptions()));
      recentMenu->addAction(act);
    }
    else
      _recent->setEnabled(false);
  }
  else
    _recent->setEnabled(false);
  
  _recent->setMenu(recentMenu);
}
예제 #6
0
QSqlDatabase databaseFromURL( const QString& databaseURL )
{
    QString protocol;
    QString hostName;
    QString dbName;
    QString port;


    parseDatabaseURL( databaseURL, protocol, hostName, dbName, port );
    QSqlDatabase db;
    /*
    if( "odbc" == protocol )
      db = QSqlDatabase::addDatabase("QODBC");
    else if ( "pgsql" == protocol || "psql" == protocol )
      db = QSqlDatabase::addDatabase("QPSQL");
    else if ( "db2" == protocol )
      db = QSqlDatabase::addDatabase("QDB2");
    else if ( "ibase" == protocol )
      db = QSqlDatabase::addDatabase("QIBASE");
    else if ( "mysql" == protocol )
      db = QSqlDatabase::addDatabase("QMYSQL");
    else if ( "oracle" == protocol )
      db = QSqlDatabase::addDatabase("QOCI");
    else if ( "sqlite" == protocol )
      db = QSqlDatabase::addDatabase("QSQLITE");
    else if ( "sqlite2" == protocol )
      db = QSqlDatabase::addDatabase("QSQLITE2");
    else if ( "sybase" == protocol )
      db = QSqlDatabase::addDatabase("QTDS");
    else
      db = QSqlDatabase::addDatabase( protocol ); // third-party or custom qt SQL drivers
    */
    db = QSqlDatabase::addDatabase("QMYSQL");
    if ( db.isValid() )
    {
        db.setDatabaseName(dbName);
        db.setHostName(hostName);
        // Check if port was provided. If not, let Qt decide, it knows default values.
        bool ok;
        int iport = port.toInt( &ok );
        if ( ok )
            db.setPort( iport );
    }
    return db;
}
예제 #7
0
QSqlDatabase databaseFromURL( const QString& databaseURL )
{
  QString protocol;
  QString hostName;
  QString dbName;
  QString port;

  parseDatabaseURL( databaseURL, protocol, hostName, dbName, port );
  QSqlDatabase db = QSqlDatabase::addDatabase(normalizeProtocol(protocol));
  if ( db.isValid() )
  {
    db.setDatabaseName(dbName);
    db.setHostName(hostName);
    // Check if port was provided. If not, let Qt decide, it knows default values.
    bool ok;
    int iport = port.toInt( &ok );
    if ( ok )
      db.setPort( iport );
  }
  return db;
}
예제 #8
0
void loginOptions::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("databaseURL", &valid);
  if (valid)
  {
    _databaseURL = param.toString();

    QString protocol;
    QString server;
    QString database;
    QString port;
    parseDatabaseURL(_databaseURL, protocol, server, database, port);
    for(int l = 0; !_driverInfoList[l].isNull(); l++)
    {
      if(_driverInfoList[l].driver == protocol ||
         _driverInfoList[l].aliases.contains(protocol))
      {
        protocol = _driverInfoList[l].name;
        break;
      }
    }
    int index = _driver->findText(protocol,Qt::MatchExactly);
    if(index == -1)
    {
        qDebug("Error, the protocol %s was not found!", protocol.toAscii().data());
	// just set something
	_driver->setCurrentIndex(0);
    } else {
	_driver->setCurrentIndex(index);
    }
    _server->setText(server);
    _database->setText(database);
    _port->setText(port);
  }
}
예제 #9
0
void login2::sLogin()
{
  QSqlDatabase db;

  QString databaseURL;
  databaseURL = _databaseURL;
  if (_demoOption->isChecked())
    databaseURL = _evalDatabaseURL.arg(_username->text().trimmed());

  QString protocol;
  QString hostName;
  QString dbName;
  QString port;
  parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);

  if (_splash)
  {
    _splash->show();
    _splash->raise();
    _splash->showMessage(tr("Initializing the Database Connector"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }

  // Open the Database Driver
  if (_multipleConnections)
    db = QSqlDatabase::addDatabase("QPSQL7", dbName);
  else
    db = QSqlDatabase::addDatabase("QPSQL7");
  if (!db.isValid())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning( this, tr("No Database Driver"),
                          tr("<p>A connection could not be established with "
                             "the specified Database as the Proper Database "
                             "Drivers have not been installed. Contact your "
                             "Systems Administator."));
    
    return;
  }

  if(hostName.isEmpty() || dbName.isEmpty())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning(this, tr("Incomplete Connection Options"),
                         tr("<p>One or more connection options are missing. "
                            "Please check that you have specified the host "
                            "name, database name, and any other required "
                            "options.") );

    return;
  }

  db.setDatabaseName(dbName);
  db.setHostName(hostName);
  db.setPort(port.toInt());

  _cUsername = _username->text().trimmed();
  _cPassword = _password->text().trimmed();

  db.setUserName(_cUsername);
  if(_demoOption->isChecked())
  {
    QString passwd = QMd5(QString(_cPassword + "private" + _cUsername)); 
    db.setPassword(passwd);
  }
  else
  {
    if(_enhancedAuth)
    {
      QString passwd = QMd5(QString(_cPassword + "xTuple" + _cUsername));
      db.setPassword(passwd);
    }
    else
      db.setPassword(_cPassword);

    if(_requireSSL)
      db.setConnectOptions("requiressl=1");
  }

  setCursor(QCursor(Qt::WaitCursor));

  if (_splash)
  {
    _splash->showMessage(tr("Connecting to the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  //  Try to connect to the Database
  bool result = db.open();
  if(!result && _enhancedAuth)
  {
    QString altpasswd = QMd5(QString(_cPassword + "OpenMFG" + _cUsername));
    db.setPassword(altpasswd);
    result = db.open();
    if(result)
    {
      altpasswd = QMd5(QString(_cPassword + "xTuple" + _cUsername));
      XSqlQuery chgpass(QString("ALTER USER %1 WITH PASSWORD '%2'").arg(_cUsername).arg(altpasswd));
    }
  }

  if (!result)
  {
    if(_requireSSL)
      db.setConnectOptions();

    if (_splash)
      _splash->hide();
    
    setCursor(QCursor(Qt::ArrowCursor));

    QMessageBox::critical(this, tr("Cannot Connect to xTuple ERP Server"),
                          tr("<p>A connection to the specified xTuple ERP "
                             "Server cannot be made.  This may be due to an "
                             "incorrect Username and/or Password or the "
                             "server in question cannot support any more "
                             "connections.<p>Please verify your Username and "
                             "Password and try again or wait until the "
                             "specified xTuple ERP Server is less busy.<br>"
                             "System Error<pre>%1" )
                            .arg(db.lastError().driverText() ));
    if (!_captive)
    {
      _username->setText("");
      _username->setFocus();
    }
    else
      _password->setFocus();

    _password->setText("");
    return;
  }

  xtsettingsSetValue("/xTuple/_demoOption", (bool)_demoOption->isChecked());

  if (_splash)
  {
    _splash->showMessage(tr("Logging into the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  if(!_nonxTupleDB)
  {
    XSqlQuery login( "SELECT login() AS result,"
                     "       CURRENT_USER AS user;" );
    setCursor(QCursor(Qt::ArrowCursor));
    if (login.first())
    {
      int result = login.value("result").toInt();
      if (result < 0)
      {
        if (_splash)
          _splash->hide();
        QMessageBox::critical(this, tr("Error Logging In"),
                              storedProcErrorLookup("login", result));
        return;
      }
      _user = login.value("user").toString();
      _databaseURL = databaseURL;
      updateRecentOptions();
      accept();
    }
    else if (login.lastError().type() != QSqlError::NoError)
    {
      if (_splash)
        _splash->hide();
      QMessageBox::critical(this, tr("System Error"),
                            tr("A System Error occurred at %1::%2:\n%1")
                              .arg(__FILE__).arg(__LINE__)
                              .arg(login.lastError().databaseText()));
    }
    else
    {
      if (_splash)
        _splash->hide();
      
      QMessageBox::critical(this, tr("System Error"),
                            tr("<p>An unknown error occurred at %1::%2. You may"
                               " not log in to the specified xTuple ERP Server "
                               "at this time.")
                              .arg(__FILE__).arg(__LINE__));
    }
  }
  else
  {
    setCursor(QCursor(Qt::ArrowCursor));
    _databaseURL = databaseURL;
    updateRecentOptions();
    accept();
  }
}
예제 #10
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;

#ifdef XQ_WS_WIN
  WSADATA wsaData;
  if (WSAStartup(MAKEWORD(1, 1), &wsaData))
  {
    qDebug("Error starting up Windows Socket system... Database services are not avalable.");
    exit(-1);
  }
#endif

  QApplication app(argc, argv);
  app.addLibraryPath(".");

#ifdef Q_WS_WIN
  if (app.winVersion() == QSysInfo::WV_XP)
    app.setStyle(QStyleFactory::create("windowsxpstyle"));
#if QT_VERSION >= 0x040300 
  else if (app.winVersion() == QSysInfo::WV_VISTA)
    app.setStyle(QStyleFactory::create("windowsvistastyle"));
#endif
  else
    app.setStyle(new QWindowsStyle);
#elif defined Q_WS_MACX
  app.setStyle(new QMacStyle);
#elif defined Q_WS_X11
  app.setStyle(new QWindowsStyle);
#endif

  // Try and load a default translation file and install it
  QTranslator defaultTranslator(0);
  if (defaultTranslator.load("default.qm", app.applicationDirPath()))
    app.installTranslator(&defaultTranslator);

  app.processEvents();

  if (argc > 1)
  {
    bool    havePasswd          = FALSE;
    bool    interactive         = TRUE;
    bool    createCountTags     = FALSE;
    QString passwd;

    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.contains("-databaseURL="))
      {
        haveDatabaseURL = TRUE;
        databaseURL = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username="******"-passwd="))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth"))
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      } 

      else if (argument.contains("-createCountTags"))
      {
        interactive = FALSE;
        createCountTags = TRUE;
      }
    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db.isValid())
      {
        qDebug("Cannot load Database Driver.  Contact your Systems Administrator.");
        exit(-1);
      }

      QString protocol;
      parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);
      db.setDatabaseName(dbName);
      db.setUserName(username);
      db.setPassword(passwd);
      db.setHostName(hostName);
      bool valport = false;
      int iport = port.toInt(&valport);
      if(!valport) iport = 5432;
      db.setPort(iport);

      if (!db.open())
      {
        qDebug( QObject::tr( "Cannot log onto the database with the supplied username/password!\n"
                             "Host = %1\n"
                             "Database = %2\n"
                             "Username = %3\n" )
                .arg(hostName)
                .arg(dbName)
                .arg(username) );
        exit(-1);
      }
      else
        loggedIn = TRUE;
    }

    if (!interactive)
      return 0;
  }

  _splash = new QSplashScreen();
  _splash->setPixmap(QPixmap(":/images/splashEmpty.png"));

  _evaluation = FALSE;

  if (!loggedIn)
  {
    ParameterList params;
//    params.append("name", _Name);  -- We can't tell now until were logged in what the app is.
    params.append("copyright", _Copyright);
    params.append("version", _Version);
    params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__));

    if (haveUsername)
      params.append("username", username);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    if (_evaluation)
      params.append("evaluation");

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, _splash);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
    else
    {
      databaseURL = newdlg._databaseURL;
      username = newdlg.username();
    }
  }

  XSqlQuery metric;
  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'Application')" );
  if(!metric.first() || (metric.value("metric_value").toString() == "OpenMFG"))
  {
    _splash->setPixmap(QPixmap(":/images/splashOpenMFG.png"));
    _Name = _Name.arg("OpenMFG");
  }
  else if(!metric.first() || (metric.value("metric_value").toString() == "xTupleERP"))
  {
    _splash->setPixmap(QPixmap(":/images/splashxTupleERP.png"));
    _Name = _Name.arg("Standard");
  }
  else
  {
    _splash->setPixmap(QPixmap(":/images/splashPostBooks.png"));
    _Name = _Name.arg("PostBooks");
  }

  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'OpenMFGServerVersion')" );
  if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion))
  {
    _splash->hide();
    int result;
    result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
      QObject::tr("The version of the database you are connecting to is not the version\n"
                  "this client was designed to work against.\n\n"
                  "This client was designed to work against the database version %1.\n"
                  "If you continue some or all functionality may not work properly\n"
                  "or at all. You may also cause other problems on the database.\n\n"
                  "Do you want to continue anyway?").arg(_dbVersion),
               QMessageBox::Yes,
               QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
    if(result != QMessageBox::Yes)
      return 0;
    _splash->show();
  }

  _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _metrics = new Metrics();

  _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _preferences = new Preferences(username);

  _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _privileges = new Privileges();

  // Load the translator and set the locale from the User's preferences
  QTranslator translator(0);
  _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  XSqlQuery langq("SELECT * "
                  "FROM usr, locale LEFT OUTER JOIN"
                  "     lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN"
                  "     country ON (locale_country_id=country_id) "
                  "WHERE ( (usr_username=CURRENT_USER)"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList paths;
    paths << "dict";
    paths << "";
    paths << "../dict";
    paths << app.applicationDirPath() + "/dict";
    paths << app.applicationDirPath();
    paths << app.applicationDirPath() + "/../dict";
#if defined Q_WS_MACX
    paths << app.applicationDirPath() + "/../../../dict";
    paths << app.applicationDirPath() + "/../../..";
#endif
    
    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    if (!langq.value("lang_abbr2").toString().isEmpty() && 
        !langq.value("country_abbr").toString().isEmpty())
    {
      files << "xTuple." + langq.value("lang_abbr2").toString() + "_" +
               langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      files << "xTuple." + langq.value("lang_abbr2").toString();
    }

    if (files.size() > 0)
    {
      bool langFound = false;

      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit)
        {
          qDebug("looking for %s in %s",
                   (*fit).toAscii().data(), (*pit).toAscii().data());
          if (translator.load(*fit, *pit))
          {
            app.installTranslator(&translator);
            langFound = true;
            break;
          }
        }
      }

      if (!langFound && !_preferences->boolean("IngoreMissingTranslationFiles"))
        QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"),
                              QObject::tr("<p>The Translation Dictionaries %1 "
                                          "cannot be loaded. Reverting "
                                          "to the default dictionary." )
                                       .arg(files.join(QObject::tr(", "))));
    }

    /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or
       lang#, depending on what information is available
     */
    QString langAbbr = langq.value("lang_abbr2").toString();
    QString cntryAbbr = langq.value("country_abbr").toString().toUpper();
    if(cntryAbbr == "UK")
      cntryAbbr = "GB";
    if (! langAbbr.isEmpty() &&
        ! cntryAbbr.isEmpty())
      QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr));
    else if (! langAbbr.isEmpty())
      QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString()));
    else if (langq.value("lang_qt_number").toInt() &&
             langq.value("country_qt_number").toInt())
      QLocale::setDefault(
          QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()),
                  QLocale::Country(langq.value("country_qt_number").toInt())));
    else
      QLocale::setDefault(QLocale::system());

    qDebug("Locale set to language %s and country %s",
           QLocale().languageToString(QLocale().language()).toAscii().data(),
           QLocale().countryToString(QLocale().country()).toAscii().data());

  }
  else if (langq.lastError().type() != QSqlError::None)
  {
    systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__);
  }

  qApp->processEvents();
  QString key;

  // TODO: Add code to check a few locations - Hopefully done

  QString keypath;
  QString keyname;
  QString keytogether;
  
  keytogether = app.applicationDirPath() + "/OpenMFG.key";
#ifdef Q_WS_WIN
  keypath = _metrics->value("CCWinEncKey");
#elif defined Q_WS_MACX
  keypath = _metrics->value("CCMacEncKey");
#elif defined Q_WS_X11
  keypath = _metrics->value("CCLinEncKey");
#endif
  
  if (keypath.isEmpty())
    keypath = app.applicationDirPath();

  if (! keypath.endsWith(QDir::separator()))
    keypath += QDir::separator();

  keyname = _metrics->value("CCEncKeyName");
  if (keyname.isEmpty())
    keyname = "OpenMFG.key";
  
  keytogether = keypath + keyname;
  
  // qDebug("keytogether: %s", keytogether.toAscii().data());
  QFile keyFile(keytogether);

  if(keyFile.exists())
  {
    if(keyFile.open(QIODevice::ReadOnly))
    {
      key = keyFile.readLine(1024);
      // strip off any newline characters
      key = key.stripWhiteSpace();
    }
  }

  omfgThis = new GUIClient(databaseURL, username);
  omfgThis->_key = key;

// qDebug("Encryption Key: %s", key.toAscii().data() );
  
  if (key.length() > 0) {
	_splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor);
	qApp->processEvents();
	_metricsenc = new Metricsenc(key);
  }
  
  initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace());

  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->show();
    app.setMainWidget(omfgThis);
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    woTimeClock* newdlg = new woTimeClock();
    ParameterList params;
    params.append("captive");
    newdlg->set(params);
    newdlg->show();
    app.setMainWidget(newdlg);
  }

  if(!omfgThis->singleCurrency())
  {
    // Check for the gain/loss and discrep accounts
    q.prepare("SELECT COALESCE((SELECT TRUE"
              "                   FROM accnt, metric"
              "                  WHERE ((CAST(accnt_id AS text)=metric_value)"
              "                    AND  (metric_name='CurrencyGainLossAccount'))), FALSE)"
              "   AND COALESCE((SELECT TRUE"
              "                   FROM accnt, metric"
              "                  WHERE ((CAST(accnt_id AS text)=metric_value)"
              "                    AND  (metric_name='GLSeriesDiscrepancyAccount'))), FALSE) AS result; ");
    q.exec();
    if(q.first() && q.value("result").toBool() != true)
      QMessageBox::warning( omfgThis, QObject::tr("Additional Configuration Required"),
        QObject::tr("Your system is configured to use multiple Currencies, but the\n"
                    "Currency Gain/Loss Account and/or the G/L Series Discrepancy Account\n"
                    "does not appear to be configured correctly. You should define these\n"
                    "Accounts in 'System | Configure Modules | Configure G/L...' before\n"
                    "posting any transactions in the system.") );
  }

  app.exec();

//  Clean up
  delete _metrics;
  delete _preferences;
  delete _privileges;
  if (0 != _metricsenc)
    delete _metricsenc;

#ifdef XQ_WS_WIN
  WSACleanup();
#endif

  return 0;
}
예제 #11
0
void login::sLogin()
{
  QSqlDatabase db;

// Open the Database Driver
  if (_splash)
  {
    _splash->show();
    _splash->message(tr("Initializing the Database Connector"));
    qApp->processEvents();
  }

  QString databaseURL;
  databaseURL = _databaseURL;
  QString protocol;
  QString hostName;
  QString dbName;
  QString port;
  parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);
  if("odbc" == protocol)
    db = QSqlDatabase::addDatabase("QODBC3");
  else
    db = QSqlDatabase::addDatabase("QPSQL7");
  if (!db.isValid())
  {
    QMessageBox::warning( this, tr("No Database Driver"),
                          tr( "A connection could not be established with the specified\n"
                              "Database as the Proper Database Drivers have not been installed.\n"
                                 "Contact your Systems Administator.\n"  ));
    
    if (_splash)
      _splash->hide();
    
    return;
  }

//  Try to connect to the Database
  db.setDatabaseName(dbName);
  db.setHostName(hostName);
  db.setPort(port.toInt());

  _cUsername = _username->text().stripWhiteSpace();
  _cPassword = _password->text().stripWhiteSpace();

  db.setUserName(_cUsername);
  db.setPassword(_cPassword);
  setCursor(QCursor(Qt::waitCursor));

  if (_splash)
  {
    _splash->message(tr("Connecting to the Database"));
    qApp->processEvents();
  }
  
  bool result = db.open();

  if (!result)
  {
    if (_splash)
      _splash->hide();
    
    setCursor(QCursor(Qt::arrowCursor));

    QMessageBox::critical( this, tr("Cannot Connect to Database Server"),
                           tr( "A connection to the specified Database Server cannot be made.  This may be due to an\n"
                               "incorrect Username and/or Password or that the Database Server in question cannot\n"
                               "support anymore connections.\n\n"
                               "Please verify your Username and Password and try again or wait until the specified\n"
                               "Database Server is less busy.\n\n"
                               "System Error '%1'" ).arg(db.lastError().driverText() ));
    if (!_captive)
    {
      _username->setText("");
      _username->setFocus();
    }
    else
      _password->setFocus();

    _password->setText("");
    return;
  }

  if (_splash)
  {
    _splash->message(tr("Logging into the Database"));
    qApp->processEvents();
  }
  
  setCursor(QCursor(Qt::arrowCursor));
  accept();
}
예제 #12
0
void login2::sLogin()
{
  QSqlDatabase db;

  QString databaseURL;
  databaseURL = _databaseURL;
  if (_demoOption->isChecked())
    databaseURL = _evalDatabaseURL.arg(_username->text().trimmed());
  else if(_cloudOption->isChecked())
    databaseURL = _cloudDatabaseURL.arg(_company->text().trimmed());

  QString protocol;
  QString hostName;
  QString dbName;
  QString port;
  parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);

  if (_splash)
  {
    _splash->show();
    _splash->raise();
    _splash->showMessage(tr("Initializing the Database Connector"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }

  // Open the Database Driver
  if (_multipleConnections)
    db = QSqlDatabase::addDatabase("QPSQL7", dbName);
  else
    db = QSqlDatabase::addDatabase("QPSQL7");
  if (!db.isValid())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning( this, tr("No Database Driver"),
                          tr("<p>A connection could not be established with "
                             "the specified Database as the Proper Database "
                             "Drivers have not been installed. Contact your "
                             "Systems Administator."));
    
    return;
  }

  if(hostName.isEmpty() || dbName.isEmpty())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning(this, tr("Incomplete Connection Options"),
                         tr("<p>One or more connection options are missing. "
                            "Please check that you have specified the host "
                            "name, database name, and any other required "
                            "options.") );

    return;
  }

  db.setDatabaseName(dbName);
  db.setHostName(hostName);
  db.setPort(port.toInt());

  _cUsername = _username->text().trimmed();
  _cPassword = _password->text().trimmed();
  _cCompany  = _company->text().trimmed();
  if(_cloudOption->isChecked())
  {
    if(_cCompany.isEmpty())
    {
      QMessageBox::warning(this, tr("Incomplete Connection Options"),
        tr("<p>You must specify the Company name to connect to the cloud."));
      return;
    }
    _cUsername = _cUsername + "_" + _cCompany;
  }

  db.setUserName(_cUsername);
  if(_demoOption->isChecked())
  {
    QString passwd = QMd5(QString(_cPassword + "private" + _cUsername)); 
    db.setPassword(passwd);
  }
  else if(_cloudOption->isChecked())
  {
    QString passwd = QMd5(QString(_cPassword + "cloudkey" + _cUsername)); 
    db.setPassword(passwd);
  }
  else
  {
    if(_enhancedAuth)
    {
      QString passwd = QMd5(QString(_cPassword + "xTuple" + _cUsername));
      db.setPassword(passwd);
    }
    else
      db.setPassword(_cPassword);

    if(_requireSSL)
      db.setConnectOptions("requiressl=1");
  }

  setCursor(QCursor(Qt::WaitCursor));

  if (_splash)
  {
    _splash->showMessage(tr("Connecting to the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  //  Try to connect to the Database
  bool result = db.open();
  if(!result && _enhancedAuth)
  {
    QString altpasswd = QMd5(QString(_cPassword + "OpenMFG" + _cUsername));
    db.setPassword(altpasswd);
    result = db.open();
    if(result)
    {
      altpasswd = QMd5(QString(_cPassword + "xTuple" + _cUsername));
      XSqlQuery chgpass(QString("ALTER USER %1 WITH PASSWORD '%2'").arg(_cUsername).arg(altpasswd));
    }
  }

  if (!result)
  {
    if(_requireSSL)
      db.setConnectOptions();

    if (_splash)
      _splash->hide();
    
    setCursor(QCursor(Qt::ArrowCursor));

    QMessageBox::critical(this, tr("Cannot Connect to xTuple ERP Server"),
                          tr("<p>Sorry, can't connect to the specified xTuple ERP server. "
                             "<p>This may be due to a problem with your user name, password, or server connection information. "
                             "<p>Below is more detail on the connection problem: "
                             "<p>%1" )
                            .arg(db.lastError().databaseText().replace('\n', "<br>") ));
    if (!_captive)
    {
      _username->setText("");
      _username->setFocus();
    }
    else
      _password->setFocus();

    _password->setText("");
    return;
  }

  xtsettingsSetValue("/xTuple/_demoOption", (bool)_demoOption->isChecked());
  xtsettingsSetValue("/xTuple/_cloudOption", (bool)_cloudOption->isChecked());
  xtsettingsSetValue("/xTuple/cloud_company", _company->text());

  if (_splash)
  {
    _splash->showMessage(tr("Logging into the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  if(!_nonxTupleDB)
  {
    XSqlQuery login( "SELECT login() AS result,"
                     "       CURRENT_USER AS user;" );
    setCursor(QCursor(Qt::ArrowCursor));
    if (login.first())
    {
      int result = login.value("result").toInt();
      if (result < 0)
      {
        if (_splash)
          _splash->hide();
        QMessageBox::critical(this, tr("Error Logging In"),
                              storedProcErrorLookup("login", result));
        return;
      }
      _user = login.value("user").toString();
      _databaseURL = databaseURL;
      updateRecentOptions();

      if (login.exec("SELECT getEffectiveXtUser() AS user;") &&
          login.first() &&
          ! login.value("user").toString().isEmpty())
        _user = login.value("user").toString();
      // no error check - older databases don't have getEffectiveXtUser

      accept();
    }
    else if (login.lastError().type() != QSqlError::NoError)
    {
      if (_splash)
        _splash->hide();
      QMessageBox::critical(this, tr("System Error"),
                            tr("A System Error occurred at %1::%2:\n%3")
                              .arg(__FILE__).arg(__LINE__)
                              .arg(login.lastError().databaseText()));
    }
    else
    {
      if (_splash)
        _splash->hide();
      
      QMessageBox::critical(this, tr("System Error"),
                            tr("<p>An unknown error occurred at %1::%2. You may"
                               " not log in to the specified xTuple ERP Server "
                               "at this time.")
                              .arg(__FILE__).arg(__LINE__));
    }
  }
  else
  {
    setCursor(QCursor(Qt::ArrowCursor));
    _databaseURL = databaseURL;
    updateRecentOptions();
    accept();
  }
}
예제 #13
0
databaseInformation::databaseInformation(QWidget* parent, const char* name, bool modal, Qt::WFlags fl)
    : XDialog(parent, name, modal, fl)
{
  setupUi(this);

  // signals and slots connections
  connect(_save, SIGNAL(clicked()), this, SLOT(sSave()));

  QString server;
  QString database;
  QString port;

  _description->setFocus();

  _description->setText(_metrics->value("DatabaseName"));
  _comments->setText(_metrics->value("DatabaseComments"));
  _version->setText(_metrics->value("OpenMFGServerVersion"));
  _patch->setText(_metrics->value("ServerPatchVersion"));

  int val = _metrics->value("updateTickInterval").toInt();
  if(val < 1) val = 1;
  _interval->setValue(val);

  //Disable batch manager if PostBooks
  if ( (_metrics->value("Application") != "OpenMFG")
    && (_metrics->value("Application") != "xTupleERP") )
  {
    _enableBatchManager->setChecked(FALSE);
    _enableBatchManager->hide();
    _defaultFromAddress->setText("");
    _defaultFromAddress->hide();
    _defaultFromAddressLit->hide();
    _purgeDaysLit->hide();
    _purgeDays->hide();
    _purgeDaysDaysLit->hide();
  }
  else
  {
    _defaultFromAddress->setText(_metrics->value("DefaultBatchFromEmailAddress"));
    _enableBatchManager->setChecked(_metrics->boolean("EnableBatchManager"));
    _purgeDays->setValue(_metrics->value("BatchManagerPurgeDays").toInt());
  }

  QString protocol;
  parseDatabaseURL(omfgThis->databaseURL(), protocol, server, database, port);
  _application->setText(_metrics->value("Application"));
  _server->setText(server);
  _name->setText(database);
  
  q.exec( "SELECT numOfDatabaseUsers() AS databaseusers,"
          "       numOfServerUsers() AS serverusers;" );
  if (q.first())
  {
    _numOfDatabaseUsers->setText(q.value("databaseusers").toString());
    _numOfServerUsers->setText(q.value("serverusers").toString());
  }
//  ToDo

  if (!_privileges->check("ConfigDatabaseInfo"))
  {
    _description->setEnabled(FALSE);
    _defaultFromAddress->setEnabled(FALSE);
    _comments->setEnabled(FALSE);
    _close->setText(tr("&Close"));
    _save->hide();
  }
}
예제 #14
0
int main(int argc, char *argv[])
{
  if (argc > 1)
  {
    QApplication application(argc, argv, FALSE);

    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;

    for (int counter = 1; counter < argc; counter++)
    {
      arguments = argv[counter];

      if (arguments.contains("-databaseURL="))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.contains("-username="******"-passwd="))
        passwd = arguments.right(arguments.length() - 8);
    }

    if (  (databaseURL != "") && (username != "") ) {
      QSqlDatabase *db;
      QString      hostName;
      QString      dbName;
      QString      port;

// Open the Database Driver
      db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db)
      {
        printf("Could not load the specified database driver.\n");
        exit(-1);
      }

//  Try to connect to the Database
      parseDatabaseURL(databaseURL, hostName, dbName, port);
      bool valport = FALSE;
      int iport = port.toInt(&valport);
      if(!valport) iport = 5432;
      db->setDatabaseName(dbName);
      db->setPort(iport);
      db->setUserName(username);
      if(!passwd.isEmpty())
        db->setPassword(passwd);
      db->setHostName(hostName);
      if (!db->open())
      {
        printf( "Host=%s, Database=%s, port=%s\n",
                (const char *)hostName,
                (const char *)dbName,
                (const char *)port );

        printf( "Could not log into database.  System Error: %s\n",
                (const char *)db->lastError().driverText() );
        exit(-1);
      }

      QSqlQuery().exec("SELECT login();");

      // first we need to determine if there is already a report in the database of the same
      // name and if so then we will perform an update instead of an insert
      QSqlQuery qry;
      qry.prepare("SELECT report_name, report_grade, report_source "
                  "  FROM report;");
      qry.exec();
      if(!qry.exec()) {
          QSqlError err = qry.lastError();
          printf("Error: %s\n\t%s\n", (const char*)err.driverText(),
                                    (const char*)err.databaseText());
          exit(-1);
      }
      QString fname;
      while(qry.next()) {
        fname = QString("%1-%2.xml").arg(qry.value(0).toString()).arg(qry.value(1).toString());
        fname.replace('/',"-");
        QFile file(fname);
        if(file.open(IO_WriteOnly))
        {
          QTextStream stream( &file );
          stream << qry.value(2).toString();
          file.close();
        }
        else
          printf("Error: Could not open file %s: %s\n", fname.latin1(), file.errorString().latin1());
      }
    }
    else if (databaseURL == "")
      printf("You must specify a Database URL by using the -databaseURL= parameter.\n");
    else if (username == "")
      printf("You must specify a Database Username by using the -username= parameter.\n");
  }
  else
    printf( "Usage: exportrpt -databaseURL='$' -username='******' -passwd='$'\n");
  return 0;
}
예제 #15
0
파일: main.cpp 프로젝트: xtuple/updater
int main(int argc, char* argv[])
{
  QSqlDatabase db;
  QString dbName;
  QString hostName;
  QString passwd;
  QString pkgfile;
  QString port;
  QString username;
  XAbstractMessageHandler *handler;
  bool    autoRunArg      = false;
  bool    autoRunCheck    = false;
  bool    debugpkg        = false;
  bool    haveDatabaseURL = false;
  bool    acceptDefaults  = false;

  QApplication app(argc, argv);
  app.addLibraryPath(".");
#ifndef Q_OS_MAC
  app.setWindowIcon(QIcon(":/images/updater-32x32.png"));
#endif

  if (argc > 1)
  {
    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.startsWith("-help", Qt::CaseInsensitive))
      {
        qWarning("%s [ -databaseURL=PSQL7://hostname:port/databasename ]"
                 " [ -h hostname ]"
                 " [ -p port ]"
                 " [ -d databasename ]"
                 " [ -U username | -username=username ]"
                 " [ -passwd=databasePassword ]"
                 " [ -debug ]"
                 " [ -file=updaterFile.gz | -f updaterFile.gz ]"
                 " [ -autorun [ -D ] ]",
                 argv[0]);
        return 0;
      }
      else if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive))
      {
        QString protocol;
        haveDatabaseURL = true;
        _databaseURL    = argument.right(argument.length() - 13);
        parseDatabaseURL(_databaseURL, protocol, hostName, dbName, port);
      }
      else if (argument == "-h")
      {
        hostName = argv[++intCounter];
      }
      else if (argument == "-p")
      {
        port = argv[++intCounter];
      }
      else if (argument == "-d")
      {
        dbName = argv[++intCounter];
      }
      else if (argument == "-U")
      {
        username = argv[++intCounter];
      }
      else if (argument.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
      {
        passwd = argument.right(argument.length() - 8);
      }
      else if (argument.toLower() == "-debug")
      {
        debugpkg = true;
      }
      else if (argument == "-f")
      {
        pkgfile = argv[++intCounter];
      }
      else if (argument.startsWith("-file=", Qt::CaseInsensitive))
      {
        pkgfile = argument.right(argument.size() - argument.indexOf("=") - 1);
      }
      else if (argument.toLower() == "-autorun")
      {
        autoRunArg = true;
      }
      else if (argument == "-D")
      {
        acceptDefaults = true;
      }
    }
  }

  LoaderWindow * mainwin = new LoaderWindow();
  mainwin->setDebugPkg(debugpkg);
  mainwin->setCmdline(autoRunArg);
  handler = mainwin->handler();
  handler->setAcceptDefaults(autoRunArg && acceptDefaults);

  ParameterList params;
  params.append("name",      Updater::name);
  params.append("copyright", Updater::copyright);
  params.append("version",   Updater::version);
  params.append("build",     Updater::build);
  if (username.length() > 0)
    params.append("username",  username);
  params.append("password",  passwd);

  if (haveDatabaseURL)
    params.append("databaseURL", _databaseURL.toLatin1().data());
  
  if (autoRunArg)
  {
    if (!haveDatabaseURL)
    {
      buildDatabaseURL(_databaseURL, "psql", hostName, dbName, port);
      params.append("databaseURL", _databaseURL.toLatin1().data());
    }
    params.append("cmd");
    params.append("login");
  }

  login2 newdlg(0, "", true);
  newdlg.set(params, 0);

  if (!QSqlDatabase::database(QSqlDatabase::defaultConnection, false).isOpen() && autoRunArg)
  {
    handler->message(QtFatalMsg,
                     QObject::tr("Unable to connect to the database "
                                 "with the given information."));
    return 1;
  }

  if (!autoRunArg)
  {
    if (newdlg.exec() == QDialog::Rejected)
      return 2;

    _databaseURL = newdlg._databaseURL;
    username     = newdlg._user;
  }

  Updater::loggedIn = true;
  mainwin->setWindowTitle();

  QSqlQuery set("SET standard_conforming_strings TO true;");
  if (set.lastError().type() != QSqlError::NoError)
    handler->message(QtWarningMsg,
                     QObject::tr("Unable to set standard_conforming_strings. "
                                 "Updates may fail with unexpected errors."));

  QSqlQuery su;
  su.prepare("SELECT rolsuper FROM pg_roles WHERE (rolname=:user);");
  su.bindValue(":user", username);
  su.exec();
  if (su.first())
  {
    if (! su.value(0).toBool() &&
        handler->question(QObject::tr("You are not logged in as a "
                                      "database super user. The update "
                                      "may fail. Are you sure you want "
                                      "to continue?"),
                          QMessageBox::Yes | QMessageBox::No,
                          QMessageBox::No) == QMessageBox::No)
      return 3;
  }
  else if (su.lastError().type() != QSqlError::NoError &&
           handler->question(QObject::tr("<p>The application received a database "
                                         "error while trying to check the user "
                                         "status of %1. Would you like to try to "
                                         "update anyway?</p><pre>%2</pre>")
                          .arg(username, su.lastError().databaseText()),
                          QMessageBox::Yes | QMessageBox::No,
                          QMessageBox::No) == QMessageBox::No)
    return 4;

  if (! pkgfile.isEmpty())
  {
    autoRunCheck = mainwin->openFile(pkgfile);
  }

  if (autoRunArg)
  {
    bool successful = autoRunCheck && ! pkgfile.isEmpty();
    if (successful)
    {
      successful = mainwin->sStart();
    }
    if (successful)     // not else if
      return 0;
    else
    {
#ifdef Q_OS_WIN32
      mainwin->show();
#else
      qWarning("%s", qPrintable(mainwin->_text->toPlainText()));
      return 5;
#endif
    }
  }
  else
    mainwin->show();

  return app.exec();
}
예제 #16
0
databaseInformation::databaseInformation(QWidget* parent, const char* name, bool /*modal*/, Qt::WFlags fl)
    : XAbstractConfigure(parent, fl)
{
  setupUi(this);

  if (name)
    setObjectName(name);

  QString server;
  QString database;
  QString port;

  if(_metrics->value("Application") != "PostBooks")
  {
    XTupleProductKey pk(_metrics->value("RegistrationKey"));
    if(pk.valid())
    {
      if(pk.users() == 0)
        _numOfServerLicencesLit->setText(tr("Open"));
      else
        _numOfServerLicencesLit->setText(QString("%1").arg(pk.users()));
    }
    else
      _numOfServerLicencesLit->setText(tr("Unknown"));
  }
  else
    _forceLicense->hide(); // doesn't apply to postbooks

  _description->setFocus();

  _description->setText(_metrics->value("DatabaseName"));
  _comments->setText(_metrics->value("DatabaseComments"));
  _version->setText(_metrics->value("ServerVersion"));
  _patch->setText(_metrics->value("ServerPatchVersion"));
  _disallowMismatchClient->setChecked(_metrics->boolean("DisallowMismatchClientVersion"));
  _forceLicense->setChecked(_metrics->boolean("ForceLicenseLimit"));

  QString access = _metrics->value("AllowedUserLogins");
  if("AdminOnly" == access)
    _access->setCurrentIndex(1);
  else if("Any" == access)
    _access->setCurrentIndex(2);
  else
    _access->setCurrentIndex(0);

  int val = _metrics->value("updateTickInterval").toInt();
  if(val < 1) val = 1;
  _interval->setValue(val);

  QString protocol;
  parseDatabaseURL(omfgThis->databaseURL(), protocol, server, database, port);
  _application->setText(_metrics->value("Application"));
  _server->setText(server);
  _name->setText(database);

  _disableAutoComplete->setChecked(_metrics->boolean("DisableAutoComplete"));
  
  q.exec( "SELECT numOfDatabaseUsers() AS databaseusers,"
          "       numOfServerUsers() AS serverusers;" );
  if (q.first())
  {
    _numOfDatabaseUsers->setText(q.value("databaseusers").toString());
    _numOfServerUsers->setText(q.value("serverusers").toString());
  }
//  ToDo

  if (!_privileges->check("ConfigDatabaseInfo"))
  {
    _description->setEnabled(FALSE);
    _comments->setEnabled(FALSE);
  }
}
예제 #17
0
void login2::sLogin()
{
  QSqlDatabase db;

// Open the Database Driver
  if (_splash)
  {
    _splash->show();
    _splash->raise();
    _splash->showMessage(tr("Initializing the Database Connector"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  db = QSqlDatabase::addDatabase("QPSQL7");
  if (!db.isValid())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning( this, tr("No Database Driver"),
                          tr( "A connection could not be established with the specified\n"
                              "Database as the Proper Database Drivers have not been installed.\n"
                                 "Contact your Systems Administator.\n"  ));
    
    return;
  }

  QString databaseURL;
  databaseURL = _databaseURL;
  if (_demoOption->isChecked())
    databaseURL = _evalDatabaseURL.arg(_username->text().stripWhiteSpace());

//  Try to connect to the Database
  QString protocol;
  QString hostName;
  QString dbName;
  QString port;
  parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);

  if(hostName.isEmpty() || dbName.isEmpty())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning(this, tr("Incomplete Connection Options"),
      tr("One or more connection options are missing. Please check that you have specified"
         " the host name, database name, and any other required options.") );

    return;
  }

  db.setDatabaseName(dbName);
  db.setHostName(hostName);
  db.setPort(port.toInt());

  _cUsername = _username->text().stripWhiteSpace();
  _cPassword = _password->text().stripWhiteSpace();

  db.setUserName(_cUsername);
  if(_demoOption->isChecked())
  {
    QString passwd = QMd5(QString(_cPassword + "private" + _cUsername)); 
    db.setPassword(passwd);
  }
  else
  {
    if(_enhancedAuth)
    {
      QString passwd = QMd5(QString(_cPassword + "OpenMFG" + _cUsername));
      db.setPassword(passwd);
    }
    else
      db.setPassword(_cPassword);

    if(_requireSSL)
      db.setConnectOptions("requiressl=1");
  }

  setCursor(QCursor(Qt::waitCursor));

  if (_splash)
  {
    _splash->showMessage(tr("Connecting to the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  bool result = db.open();

  if (!result)
  {
    if(_requireSSL)
      db.setConnectOptions();

    if (_splash)
      _splash->hide();
    
    setCursor(QCursor(Qt::arrowCursor));

    QMessageBox::critical( this, tr("Cannot Connect to OpenMFG Server"),
                           tr( "A connection to the specified OpenMFG Server cannot be made.  This may be due to an\n"
                               "incorrect Username and/or Password or that the OpenMFG Server in question cannot\n"
                               "support anymore connections.\n\n"
                               "Please verify your Username and Password and try again or wait until the specified\n"
                               "OpenMFG Server is less busy.\n\n"
                               "System Error '%1'" ).arg(db.lastError().driverText() ));
    if (!_captive)
    {
      _username->setText("");
      _username->setFocus();
    }
    else
      _password->setFocus();

    _password->setText("");
    return;
  }

  QSettings settings(QSettings::UserScope, "OpenMFG.com", "OpenMFG");
  settings.writeEntry("/OpenMFG/_demoOption", (bool)_demoOption->isChecked());

  if (_splash)
  {
    _splash->showMessage(tr("Logging into the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  if(!_nonOpenMFGDB)
  {
    XSqlQuery login( "SELECT login() AS usr_id,"
                     "       CURRENT_USER AS user;" );
    setCursor(QCursor(Qt::arrowCursor));
    if (login.first())
    {
      switch (login.value("usr_id").toInt())
      {
        case -1:
          if (_splash)
            _splash->hide();
  
          QMessageBox::critical( this, tr("User does not Exist"),
                                 tr( "The specified Username does not exist in the specified Database.\n"
                                     "Contact your Systems Administrator to report this issue." ) );
          break;
  
        case -2:
          if (_splash)
            _splash->hide();
  
          QMessageBox::critical( this, tr("User is Inactive"),
                                 tr( "The specified Username does exists in the specified Database but is not Active.\n"
                                     "Contact your Systems Administrator to report this issue." ) );
          break;
  
        default:
          _user = login.value("user").toString();
          _userid = login.value("usr_id").toInt();
          _databaseURL = databaseURL;
          accept();
          break;
      }
    }
    else
    {
      if (_splash)
        _splash->hide();
      
      QMessageBox::critical( this, tr("System Error"),
                             tr( "A System Error occurred at login2::%1.\n"
                                 "You may not log into the specified OpenMFG Server at this time.\n"
                                 "Report this to your Systems Administrator." )
                             .arg(__LINE__) );
    }
  }
  else
  {
    setCursor(QCursor(Qt::arrowCursor));
    _databaseURL = databaseURL;
    accept();
  }
}
예제 #18
0
파일: main.cpp 프로젝트: gpazo/xtuple-svn
int main(int argc, char* argv[])
{
  QString username  = "";
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  _loggedIn        = FALSE;
  bool multitrans = false;
  bool debugpkg   = false;
  QString pkgfile = "";

  QApplication app(argc, argv);
  app.addLibraryPath(".");
#ifndef Q_WS_MACX
  app.setWindowIcon(QIcon(":/images/updater-32x32.png"));
#endif

  if (argc > 1)
  {
    haveUsername        = FALSE;
    bool    havePasswd          = FALSE;
    QString passwd              = "";

    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive)) {
        haveDatabaseURL = TRUE;
        _databaseURL    = argument.right(argument.length() - 13);
      }
      else if (argument.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.toLower() == "-noauth")
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      }
      else if (argument.toLower() == "-multitrans")
        multitrans = true;
      else if (argument.toLower() == "-debug")
        debugpkg = true;
      else if (argument.startsWith("-file=", Qt::CaseInsensitive))
        pkgfile = argument.right(argument.size() - argument.indexOf("=") - 1);
    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db.isValid())
      {
        QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the databse driver. Please contact your systems adminstrator."));
        QApplication::exit(-1);
      }

      parseDatabaseURL(_databaseURL, protocol, hostName, dbName, port);
      db.setDatabaseName(dbName);
      db.setUserName(username);
      db.setPassword(passwd);
      db.setHostName(hostName);
      db.setPort(port.toInt());

      if (!db.open())
      {
        QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information."));
        QApplication::exit(-1);
      }
      else
        _loggedIn = TRUE;
    }

  }

  if(!_loggedIn)
  {
    ParameterList params;
    params.append("name", _name);
    params.append("copyright", _copyright.toAscii().data());
    params.append("version",   _version.toAscii().data());
    params.append("build", __DATE__ " " __TIME__); // use C++ string concat

    if (haveUsername)
      params.append("username", _user);

    if (haveDatabaseURL)
      params.append("databaseURL", _databaseURL.toAscii().data());

    if (_evaluation)
      params.append("evaluation");

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, 0);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
    else
    {
      _databaseURL = newdlg._databaseURL;
      _user = newdlg._user;
      _loggedIn = TRUE;
    }

    QSqlQuery su;
    su.prepare("SELECT rolsuper FROM pg_roles WHERE (rolname=:user);");
    su.bindValue(":user", _user);
    su.exec();
    if (su.first())
    {
      if (! su.value(0).toBool() &&
          QMessageBox::question(0, QObject::tr("Not Super User"),
                                QObject::tr("You are not logged in as a "
                                            "database super user. The update "
                                            "may fail. Are you sure you want "
                                            "to continue?"),
                                QMessageBox::Yes,
                                QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
        return -2;
    }
    else if (su.lastError().type() != QSqlError::NoError &&
             QMessageBox::question(0, QObject::tr("System Error"),
                            QObject::tr("<p>The application received a database "
                                        "error while trying to check the user "
                                        "status of %1. Would you like to try to "
                                        "update anyway?<br><pre>%2")
                            .arg(_user)
                            .arg(su.lastError().databaseText()),
                            QMessageBox::Yes,
                            QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
      return -3;
  }

  LoaderWindow * mainwin = new LoaderWindow();
  mainwin->setMultipleTransactions(multitrans);
  mainwin->setDebugPkg(debugpkg);
  if (! pkgfile.isEmpty())
    mainwin->openFile(pkgfile);
  mainwin->show();

  return app.exec();
}
예제 #19
0
void login2::sLogin()
{
  QSqlDatabase db;

  QString databaseURL;
  databaseURL = _databaseURL;
  /*
  if(_cloudOption->isChecked())
  {
    if(_demoOption->isChecked())
      databaseURL = _cloudDatabaseURL.arg(_company->text().trimmed(), "demo");
    else
      databaseURL = _cloudDatabaseURL.arg(_company->text().trimmed(), "quickstart");
  }
  */

  QString protocol;
  QString hostName;
  QString dbName;
  QString port;
  parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);

  if (_splash)
  {
    _splash->show();
    _splash->raise();
    _splash->showMessage(tr("Initializing the Database Connector"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }

  // Open the Database Driver
  if (_multipleConnections)
    db = QSqlDatabase::addDatabase("QPSQL7", dbName);
  else
    db = QSqlDatabase::addDatabase("QPSQL7");
  if (!db.isValid())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning( this, tr("No Database Driver"),
                          tr("<p>A connection could not be established with "
                             "the specified Database as the Proper Database "
                             "Drivers have not been installed. Contact your "
                             "Systems Administator."));
    
    return;
  }

  if(hostName.isEmpty() || dbName.isEmpty())
  {
    if (_splash)
      _splash->hide();
    
    QMessageBox::warning(this, tr("Incomplete Connection Options"),
                         tr("<p>One or more connection options are missing. "
                            "Please check that you have specified the host "
                            "name, database name, and any other required "
                            "options.") );

    return;
  }

  db.setDatabaseName(dbName);
  db.setHostName(hostName);
  db.setPort(port.toInt());

  _cUsername = _username->text().trimmed();
  _cPassword = _password->text().trimmed();
  //_cCompany  = _company->text().trimmed();

  setCursor(QCursor(Qt::WaitCursor));
  qApp->processEvents();

  if (_splash)
  {
    _splash->showMessage(tr("Connecting to the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }

  /*
  if(_cloudOption->isChecked())
  {
    if(_cCompany.isEmpty())
    {
      QMessageBox::warning(this, tr("Incomplete Connection Options"),
        tr("<p>You must specify the Cloud ID name to connect to the cloud."));
      return;
    }
  }
  */

  db.setUserName(_cUsername);

  QRegExp xtuplecloud(".*\\.xtuplecloud\\.com");
  QRegExp xtuple(".*\\.xtuple\\.com");

  bool isCloud = xtuplecloud.exactMatch(hostName);
  bool isXtuple = xtuple.exactMatch(hostName);
  QString salt;

  if(isCloud || isXtuple)
  {
    salt = "private";
  }
  else
  {
    salt = "xTuple";
  }

  // try connecting to the database in each of the following ways in this order
  QList<QPair<QString, QString> > method;
  method << QPair<QString, QString>("requiressl=1", QMd5(QString(_cPassword + salt  + _cUsername)))
         << QPair<QString, QString>("requiressl=1", _cPassword)
         << QPair<QString, QString>("requiressl=1", QMd5(QString(_cPassword + "OpenMFG" + _cUsername)))
         << QPair<QString, QString>("",             QMd5(QString(_cPassword + salt  + _cUsername)))
         << QPair<QString, QString>("",             _cPassword)
         << QPair<QString, QString>("",             QMd5(QString(_cPassword + "OpenMFG" + _cUsername)))
      ;
  int methodidx; // not declared in for () because we'll need it later
  for (methodidx = 0; methodidx < method.size(); methodidx++)
  {
    db.setConnectOptions(method.at(methodidx).first);
    db.setPassword(method.at(methodidx).second);
    if (db.open())
      break;  // break instead of for-loop condition to preserve methodidx
  }

  // if connected using OpenMFG enhanced auth, remangle the password
  if (db.isOpen() && (methodidx == 2 || methodidx == 5))
      XSqlQuery chgpass(QString("ALTER USER \"%1\" WITH PASSWORD '%2'")
                      .arg(_cUsername, QMd5(QString(_cPassword + "xTuple" + _cUsername))));
  else if (db.isOpen() && method.at(methodidx).first.isEmpty())
  {
    XSqlQuery sslq("SHOW ssl;");
    //TODO: Add SSL to installer and require it by default for all xTuple users
    /*if (sslq.first() && sslq.value("ssl").toString() != "on")
      QMessageBox::warning(this, tr("Could Not Enforce Security"),
                           tr("The connection to the xTuple ERP Server is not "
                              "secure. Please ask your administrator to set "
                              "the 'ssl' configuration option to 'on'."));*/
  }

  if (! db.isOpen())
  {
    if (_splash)
      _splash->hide();
    
    setCursor(QCursor(Qt::ArrowCursor));

    QMessageBox::critical(this, tr("Cannot Connect to xTuple ERP Server"),
                          tr("<p>Sorry, can't connect to the specified xTuple ERP server. "
                             "<p>This may be due to a problem with your user name, password, or server connection information. "
                             "<p>Below is more detail on the connection problem: "
                             "<p>%1" ).arg(db.lastError().text()));

    if (!_captive)
    {
      _username->setText("");
      _username->setFocus();
    }
    else
      _password->setFocus();

    _password->setText("");
    return;
  }

  /*
  xtsettingsSetValue("/xTuple/_demoOption", (bool)_demoOption->isChecked());
  xtsettingsSetValue("/xTuple/_cloudOption", (bool)_cloudOption->isChecked());
  xtsettingsSetValue("/xTuple/cloud_company", _company->text());
  */

  if (_splash)
  {
    _splash->showMessage(tr("Logging into the Database"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
  }
  
  if(!_nonxTupleDB)
  {
    QString loginqry = "";
    if (_setSearchPath)
      loginqry="SELECT login(true) AS result, CURRENT_USER AS user;";
    else
      loginqry="SELECT login() AS result, CURRENT_USER AS user;";
    XSqlQuery login( loginqry );
    setCursor(QCursor(Qt::ArrowCursor));
    if (login.first())
    {
      int result = login.value("result").toInt();
      if (result < 0)
      {
        if (_splash)
          _splash->hide();
        QMessageBox::critical(this, tr("Error Logging In"),
                              storedProcErrorLookup("login", result));
        return;
      }
      _user = login.value("user").toString();
      _databaseURL = databaseURL;
      updateRecentOptions();

      if (login.exec("SELECT getEffectiveXtUser() AS user;") &&
          login.first() &&
          ! login.value("user").toString().isEmpty())
        _user = login.value("user").toString();
      // no error check - older databases don't have getEffectiveXtUser

      accept();
    }
    else if (login.lastError().type() != QSqlError::NoError)
    {
      if (_splash)
        _splash->hide();
      QMessageBox::critical(this, tr("System Error"),
                            tr("A System Error occurred at %1::%2:\n%3")
                              .arg(__FILE__).arg(__LINE__)
                              .arg(login.lastError().databaseText()));
    }
    else
    {
      if (_splash)
        _splash->hide();
      
      QMessageBox::critical(this, tr("System Error"),
                            tr("<p>An unknown error occurred at %1::%2. You may"
                               " not log in to the specified xTuple ERP Server "
                               "at this time.")
                              .arg(__FILE__).arg(__LINE__));
    }
  }
  else
  {
    setCursor(QCursor(Qt::ArrowCursor));
    _databaseURL = databaseURL;
    updateRecentOptions();
    accept();
  }
}
예제 #20
0
int main(int argc, char *argv[])
{
  QString username  = "";
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  _loggedIn        = FALSE;

  _databaseURL = "";

  QApplication app(argc, argv);
  app.addLibraryPath(".");

#ifdef Q_WS_WIN
  if (app.winVersion() == Qt::WV_XP)
    app.setStyle(QStyleFactory::create("windowsxpstyle"));
  else
    app.setStyle(new QWindowsStyle);
#elif defined Q_WS_MACX
  app.setStyle(new QMacStyle);
#else
  app.setStyle(new QWindowsStyle);
#endif

  if (argc > 1)
  {
    haveUsername        = FALSE;
    bool    havePasswd          = FALSE;
    QString passwd              = "";

    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.contains("-databaseURL=")) {
        haveDatabaseURL = TRUE;
        _databaseURL    = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username="******"-passwd="))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth"))
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      } 

    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase *db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

      parseDatabaseURL(_databaseURL, protocol, hostName, dbName, port);
      if("odbc" == protocol)
        db = QSqlDatabase::addDatabase("QODBC3");  
      else
        db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db)
      {
        QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the databse driver. Please contact your systems adminstrator."));
        QApplication::exit(-1);
      }

      db->setDatabaseName(dbName);
      db->setUserName(username);
      db->setPassword(passwd);
      db->setHostName(hostName);
      db->setPort(port.toInt());

      if (!db->open())
      {
        QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information."));
        QApplication::exit(-1);
      }
      else
        _loggedIn = TRUE;
    }

  }

  MQLEdit * mainwin = new MQLEdit();
  mainwin->show();

  app.setMainWidget(mainwin);
  return app.exec();
}
예제 #21
0
void company::sTest()
{
  XSqlQuery companyTest;
  if (DEBUG)
    qDebug("company::sTest()");

  QString dbURL;
  QString protocol = "psql";
  QString host = _extServer->text();
  QString db   = _extDB->text();
  QString port = _extPort->cleanText();

  buildDatabaseURL(dbURL, protocol, host, db, port);
  if (DEBUG)
    qDebug("company::sTest() dbURL before login2 = %s", qPrintable(dbURL));

  ParameterList params;
  params.append("databaseURL", dbURL);
  params.append("multipleConnections");
  params.append("applicationName", _ConnAppName);

  login2 newdlg(this, "testLogin", false);
  newdlg.set(params);
  if (newdlg.exec() == QDialog::Rejected)
    return;

  dbURL = newdlg._databaseURL;
  if (DEBUG)
    qDebug("company::sTest() dbURL after login2 = %s", qPrintable(dbURL));
  parseDatabaseURL(dbURL, protocol, host, db, port);

  QSqlDatabase testDB = QSqlDatabase::addDatabase("QPSQL7", db);
  testDB.setHostName(host);
  testDB.setDatabaseName(db);
  testDB.setUserName(newdlg.username());
  testDB.setPassword(newdlg.password());
  testDB.setPort(port.toInt());
  if (testDB.open())
  {
    if (DEBUG)
      qDebug("company::sTest() opened testDB!");

    XSqlQuery rmq(testDB);
    rmq.prepare("SELECT fetchMetricText('ServerVersion') AS result;");
    rmq.exec();
    if (rmq.first())
    {
      if (rmq.value("result").toString() != _metrics->value("ServerVersion"))
      {
        QMessageBox::warning(this, tr("Versions Incompatible"),
                             tr("<p>The version of the child database is not "
                                "the same as the version of the parent "
                                "database (%1 vs. %2). The data cannot safely "
                                "be synchronized.")
                             .arg(rmq.value("result").toString())
                             .arg(_metrics->value("ServerVersion")));
        return;
      }
    }
    else if (rmq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, rmq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }

    rmq.exec("SELECT * FROM curr_symbol WHERE curr_base;");
    if (_external->isChecked())
    {
      companyTest.prepare("SELECT * FROM curr_symbol WHERE curr_id=:curr_id;");
      companyTest.bindValue(":curr_id", _currency->id());
      companyTest.exec();
    }
    else
      companyTest.exec("SELECT * FROM curr_symbol WHERE curr_base;");

    if (companyTest.first() && rmq.first())
    {
      if (rmq.value("curr_symbol").toString() != companyTest.value("curr_symbol").toString() &&
          rmq.value("curr_abbr").toString() != companyTest.value("curr_abbr").toString())
      {
        QMessageBox::warning(this, tr("Currencies Incompatible"),
                             tr("<p>The currency of the child database does "
                                "not appear to match the selected currency for "
                                "the company (%1 %2 %3 vs. %4 %5 %6). The data may "
                                "not synchronize properly.")
                             .arg(rmq.value("curr_name").toString())
                             .arg(rmq.value("curr_symbol").toString())
                             .arg(rmq.value("curr_abbr").toString())
                             .arg(companyTest.value("curr_name").toString())
                             .arg(companyTest.value("curr_symbol").toString())
                             .arg(companyTest.value("curr_abbr").toString()));
        return;
      }
    }
    else if (rmq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, rmq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (companyTest.lastError().type() != QSqlError::NoError)
    {
      systemError(this, companyTest.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else if (!rmq.first())
    {
      QMessageBox::warning(this, tr("No Base Currency"),
                           tr("<p>The child database does not appear to have "
                              "a base currency defined. The data cannot safely "
                              "be synchronized."));
      return;
    }
    else if (!companyTest.first())
    {
      QMessageBox::warning(this, tr("No Base Currency"),
                           tr("<p>The parent database does not appear to have "
                              "a base currency defined. The data cannot safely "
                              "be synchronized."));
      return;
    }

    rmq.prepare("SELECT * FROM company WHERE (company_number=:number);");
    rmq.bindValue(":number", _number->text());
    rmq.exec();
    if (rmq.first())
    {
      QMessageBox::warning(this, windowTitle(), tr("Test Successful."));
      return;
    }
    else if (rmq.lastError().type() != QSqlError::NoError)
    {
      systemError(this, rmq.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
    else
    {
      QMessageBox::warning(this, tr("No Corresponding Company"),
                           tr("<p>The child database does not appear to have "
                              "a Company %1 defined. The data cannot safely "
                              "be synchronized.").arg(_number->text()));
      return;
    }
  }
}
예제 #22
0
int main(int argc, char *argv[])
{
  if (argc > 1)
  {
    QApplication application(argc, argv, FALSE);
    application.addLibraryPath(".");

    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;

    QString xml_file = QString::null;
    int     report_grade = 0;

    for (int counter = 1; counter < argc; counter++)
    {
      arguments = argv[counter];

      if (arguments.contains("-databaseURL="))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.contains("-username="******"-passwd="))
        passwd = arguments.right(arguments.length() - 8);
      else if (arguments.contains("-f="))
        xml_file = arguments.right(arguments.length() - 3);
      else if (arguments.contains("-grade="))
        report_grade = (arguments.right(arguments.length() - 7)).toInt();
    }

    QString report_name = QString::null;
    QString report_desc = QString::null;
    QString report_src  = QString::null;

    if(xml_file != "") {
        QFile file(xml_file);
        if(file.open( IO_ReadOnly )) {
            QDomDocument doc;
            QString errMsg;
            int errLine, errCol;
            if(doc.setContent(&file, &errMsg, &errLine, &errCol)) {
                QDomElement root = doc.documentElement();
                if(root.tagName() == "report") {
                    for(QDomNode n = root.firstChild();
                            !n.isNull(); n = n.nextSibling() ) {
                        if(n.nodeName() == "name") {
                            report_name = n.firstChild().nodeValue();
                        } else if(n.nodeName() == "description") {
                            report_desc = n.firstChild().nodeValue();
                        }
                    }
                    report_src  = doc.toString();

                    if(report_name == "") {
                        printf("The document %s does not have a report name defined\n", (const char*)xml_file);
                    }
                } else {
                    printf("XML Document %s does not have root node of report\n",(const char*)xml_file);
                }
            } else {
                printf("Error parsing file %s: %s on line %d column %d\n",
                    (const char*)xml_file, (const char*)errMsg, errLine, errCol);
            }
        } else {
            printf("Could not open the specified file: %s\n", (const char*)xml_file);
        }
    } else {
        printf("You must specify an XML file to load by using the -f= parameter.\n");
    }

    if(report_name == "" || report_src == "") {
        // an error message already should have been displayed to the user
        exit(-1);
    }

    if (  (databaseURL != "") &&
          (username != "")    &&
          (passwd != "")          ) {
      QSqlDatabase *db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

// Open the Database Driver
      parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);
      if("odbc" == protocol)
        db = QSqlDatabase::addDatabase("QODBC3");  
      else
        db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db)
      {
        printf("Could not load the specified database driver.\n");
        exit(-1);
      }

//  Try to connect to the Database
      bool valport = FALSE;
      int iport = port.toInt(&valport);
      if(!valport) iport = 5432;
      db->setDatabaseName(dbName);
      db->setPort(iport);
      db->setUserName(username);
      db->setPassword(passwd);
      db->setHostName(hostName);
      if (!db->open())
      {
        printf( "Host=%s, Database=%s, port=%s\n",
                (const char *)hostName,
                (const char *)dbName,
                (const char *)port );

        printf( "Could not log into database.  System Error: %s\n",
                (const char *)db->lastError().driverText() );
        exit(-1);
      }

      QSqlQuery().exec("SELECT login();");

      // first we need to determine if there is already a report in the database of the same
      // name and if so then we will perform an update instead of an insert
      QSqlQuery qry;
      qry.prepare("SELECT report_id "
                  "  FROM report "
                  " WHERE ((report_name=:report_name) "
                  "   AND (report_grade=:report_grade));");
      qry.bindValue(":report_name", report_name);
      qry.bindValue(":report_grade", report_grade);
      qry.exec();
      QSqlQuery query;
      if(qry.first()) {
          // update
          query.prepare("UPDATE report "
                        "   SET report_descrip=:report_desc, "
                        "       report_source =:report_src "
                        " WHERE ((report_id=:report_id) "
                        "   AND (report_name=:report_name));");
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_id", qry.value(0));
          query.bindValue(":report_name", report_name);
      } else {
          // insert
          query.prepare("INSERT INTO report "
                        "       (report_name, report_descrip, report_source, report_grade) "
                        "VALUES (:report_name, :report_desc, :report_src, :report_grade);");
          query.bindValue(":report_name", report_name);
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_grade", report_grade);
      }
      
      if(!query.exec()) {
          QSqlError err = query.lastError();
          printf("Error: %s\n\t%s\n", (const char*)err.driverText(),
                                    (const char*)err.databaseText());
          exit(-1);
      }
      
    }
    else if (databaseURL == "")
      printf("You must specify a Database URL by using the -databaseURL= parameter.\n");
    else if (username == "")
      printf("You must specify a Database Username by using the -username= parameter.\n");
    else if (passwd == "")
      printf("You must specify a Database Password by using the -passwd= parameter.\n");
  }
  else
    printf( "Usage: import -databaseURL='$' -username='******' -passwd='$' -grade=# -f='$'\n");
  return 0;
}
예제 #23
0
int main(int argc, char *argv[])
{
  QCoreApplication application(argc, argv);
  application.addLibraryPath(".");

  QTextStream out(stdout, QIODevice::WriteOnly);

  if (argc > 1)
  {
    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;
    QString dbServer = QString::null;


    for (int counter = 1; counter < argc; counter++)
    {
      QString arguments(argv[counter]);

      if (arguments.startsWith("-databaseURL=", Qt::CaseInsensitive))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
        passwd = arguments.right(arguments.length() - 8);
      else if (arguments.startsWith("-dbengine=", Qt::CaseInsensitive))
        dbServer = arguments.right(arguments.length() - 10);
    }


    if (  (databaseURL != "") &&
          (username != "")    &&
          (passwd != "")          ) 
    {

      QSqlDatabase db;
      QString protocol = QString::null;
      QString server   = QString::null;
      QString database = QString::null;
      QString port     = QString::null;

      // Note: parseDatabaseURL returns a default port of 5432 (Default Postgresql port)
      //       is this a bug or a feature ?
      parseDatabaseURL(databaseURL, protocol, server, database, port);

      // treat odbc connections as a special case
      if ( protocol == "odbc")
      {
        if ( dbServer == QString::null )
        {
          out << " database URL = " << databaseURL << endl;
          out << "Protocol=" << protocol << ", Host=" << server << ", Database=" << database << ", port=" << port << endl;
          out << "\"--dbengine=\" parameter required when url protocol is odbc" << endl;
          exit(EXIT_ERROR_MISSING_DB_ENGINE);
        }
        if (! isValidProtocol(dbServer, false) )
        {
          out << "Unrecognised database server: [--dbengine=" << dbServer << "]" << endl;
          out << "Protocol=" << protocol << ", Host=" << server << ", Database=" << database << ", port=" << port << endl;
          exit(EXIT_ERROR_DB_ENGINE);
        }
      }

      // Open the Database Driver
      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        out << " database URL = " << databaseURL << endl;
        out << "Protocol=" << protocol << ", Host=" << server << ", Database=" << database << ", port=" << port << endl;
        out << "Could not load the specified database driver." << endl;
        exit(EXIT_ERROR_DB_DRIVER);
      }

      //  Try to connect to the Database
      db.setUserName(username);
      db.setPassword(passwd);
      if (!db.open())
      {
        out << "Protocol=" << protocol << ", Host=" << db.hostName() << 
              ", Database=" << db.databaseName() << ", port=" << db.port() << endl;
        out << "Could not log into database.  System Error: "
            << db.lastError().text() << endl;
        exit(EXIT_ERROR_DB_LOGIN);
      }

      if ( ! buildTable(db, out, dbServer) ) 
        exit(EXIT_ERROR_DB_TABLE_BUILD);
    }
    else if (databaseURL == "")
    {
      out << "You must specify a Database URL by using the -databaseURL= parameter." << endl;
      exit(EXIT_ERROR_MISSING_URL);
    }
    else if (username == "")
    {
      out << "You must specify a Database Username by using the -username= parameter." << endl;
      exit(EXIT_ERROR_MISSING_USERNAME);
    }
    else if (passwd == "")
    {
      out << "You must specify a Database Password by using the -passwd= parameter." << endl;
      exit(EXIT_ERROR_MISSING_PASSWORD);
    }
  }
  else
  {
    out << "Usage: bldtbls -databaseURL='$' -username='******' -passwd='$' [-dbengine='$']" << endl;
    exit(EXIT_ERROR_BAD_ARGS);
  }

  return EXIT_SUCCESS;
}