예제 #1
0
/*!
    Cleans the cache so that its size is under the maximum cache size.
    Returns the current size of the cache.

    When the current size of the cache is greater than the maximumCacheSize()
    older cache files are removed until the total size is less then 90% of
    maximumCacheSize() starting with the oldest ones first using the file
    creation date to determine how old a cache file is.

    Subclasses can reimplement this function to change the order that cache
    files are removed taking into account information in the application
    knows about that QNetworkDiskCache does not, for example the number of times
    a cache is accessed.

    Note: cacheSize() calls expire if the current cache size is unknown.

    \sa maximumCacheSize(), fileMetaData()
 */
qint64 QNetworkDiskCache::expire()
{
    Q_D(QNetworkDiskCache);
    if (d->currentCacheSize >= 0 && d->currentCacheSize < maximumCacheSize())
        return d->currentCacheSize;

    if (cacheDirectory().isEmpty()) {
        qWarning() << "QNetworkDiskCache::expire() The cache directory is not set";
        return 0;
    }

    // close file handle to prevent "in use" error when QFile::remove() is called
    d->lastItem.reset();

    QDir::Filters filters = QDir::AllDirs | QDir:: Files | QDir::NoDotAndDotDot;
    QDirIterator it(cacheDirectory(), filters, QDirIterator::Subdirectories);

    QMultiMap<QDateTime, QString> cacheItems;
    qint64 totalSize = 0;
    while (it.hasNext()) {
        QString path = it.next();
        QFileInfo info = it.fileInfo();
        QString fileName = info.fileName();
        if (fileName.endsWith(CACHE_POSTFIX)) {
            cacheItems.insert(info.created(), path);
            totalSize += info.size();
        }
    }

    int removedFiles = 0;
    qint64 goal = (maximumCacheSize() * 9) / 10;
    QMultiMap<QDateTime, QString>::const_iterator i = cacheItems.constBegin();
    while (i != cacheItems.constEnd()) {
        if (totalSize < goal)
            break;
        QString name = i.value();
        QFile file(name);
        qint64 size = file.size();
        file.remove();
        totalSize -= size;
        ++removedFiles;
        ++i;
    }
#if defined(QNETWORKDISKCACHE_DEBUG)
    if (removedFiles > 0) {
        qDebug() << "QNetworkDiskCache::expire()"
                << "Removed:" << removedFiles
                << "Kept:" << cacheItems.count() - removedFiles;
    }
#endif
    return totalSize;
}
예제 #2
0
QString XmppUriQueries::makeXmppUri(const Jid &AContactJid, const QString &AAction, const QMultiMap<QString, QString> &AParams) const
{
	if (AContactJid.isValid() && !AAction.isEmpty())
	{
		QUrl url;
		url.setQueryDelimiters('=',';');

		url.setScheme(XMPP_URI_SCHEME);
		url.setPath(AContactJid.full());

		QList< QPair<QString, QString> > query;
		query.append(qMakePair<QString,QString>(AAction,QString::null));
		for(QMultiMap<QString, QString>::const_iterator it=AParams.constBegin(); it!=AParams.end(); ++it)
			query.append(qMakePair<QString,QString>(it.key(),it.value()));
		url.setQueryItems(query);

		return url.toString().replace(QString("?%1=;").arg(AAction),QString("?%1;").arg(AAction));
	}
	return QString::null;
}
bool QgsGeometryAnalyzer::dissolve( QgsVectorLayer* layer, const QString& shapefileName,
                                    bool onlySelectedFeatures, int uniqueIdField, QProgressDialog* p )
{
  if ( !layer )
  {
    return false;
  }
  QgsVectorDataProvider* dp = layer->dataProvider();
  if ( !dp )
  {
    return false;
  }
  bool useField = false;
  if ( uniqueIdField == -1 )
  {
    uniqueIdField = 0;
  }
  else
  {
    useField = true;
  }

  QgsWkbTypes::Type outputType = dp->wkbType();
  QgsCoordinateReferenceSystem crs = layer->crs();

  QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), layer->fields(), outputType, crs );
  QgsFeature currentFeature;
  QMultiMap<QString, QgsFeatureId> map;

  if ( onlySelectedFeatures )
  {
    //use QgsVectorLayer::featureAtId
    const QgsFeatureIds selection = layer->selectedFeaturesIds();
    QgsFeatureIds::const_iterator it = selection.constBegin();
    for ( ; it != selection.constEnd(); ++it )
    {
      if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( currentFeature ) )
      {
        continue;
      }
      map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
    }
  }
  else
  {
    QgsFeatureIterator fit = layer->getFeatures();
    while ( fit.nextFeature( currentFeature ) )
    {
      map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
    }
  }

  QgsGeometry dissolveGeometry; //dissolve geometry
  QMultiMap<QString, QgsFeatureId>::const_iterator jt = map.constBegin();
  QgsFeature outputFeature;
  while ( jt != map.constEnd() )
  {
    QString currentKey = jt.key();
    int processedFeatures = 0;
    bool first = true;
    //take only selection
    if ( onlySelectedFeatures )
    {
      //use QgsVectorLayer::featureAtId
      const QgsFeatureIds selection = layer->selectedFeaturesIds();
      if ( p )
      {
        p->setMaximum( selection.size() );
      }
      while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
      {
        if ( p && p->wasCanceled() )
        {
          break;
        }
        if ( selection.contains( jt.value() ) )
        {
          if ( p )
          {
            p->setValue( processedFeatures );
          }
          if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( jt.value() ) ).nextFeature( currentFeature ) )
          {
            continue;
          }
          if ( first )
          {
            outputFeature.setAttributes( currentFeature.attributes() );
            first = false;
          }
          dissolveGeometry = dissolveFeature( currentFeature, dissolveGeometry );
          ++processedFeatures;
        }
        ++jt;
      }
    }
    //take all features
    else
    {
      int featureCount = layer->featureCount();
      if ( p )
      {
        p->setMaximum( featureCount );
      }
      while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
      {
        if ( p )
        {
          p->setValue( processedFeatures );
        }

        if ( p && p->wasCanceled() )
        {
          break;
        }
        if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( jt.value() ) ).nextFeature( currentFeature ) )
        {
          continue;
        }
        {
          outputFeature.setAttributes( currentFeature.attributes() );
          first = false;
        }
        dissolveGeometry = dissolveFeature( currentFeature, dissolveGeometry );
        ++processedFeatures;
        ++jt;
      }
    }
    outputFeature.setGeometry( dissolveGeometry );
    vWriter.addFeature( outputFeature );
  }
  return true;
}
bool QgsGeometryAnalyzer::convexHull( QgsVectorLayer* layer, const QString& shapefileName,
                                      bool onlySelectedFeatures, int uniqueIdField, QProgressDialog* p )
{
  if ( !layer )
  {
    return false;
  }
  QgsVectorDataProvider* dp = layer->dataProvider();
  if ( !dp )
  {
    return false;
  }
  bool useField = false;
  if ( uniqueIdField == -1 )
  {
    uniqueIdField = 0;
  }
  else
  {
    useField = true;
  }
  QgsFields fields;
  fields.append( QgsField( QStringLiteral( "UID" ), QVariant::String ) );
  fields.append( QgsField( QStringLiteral( "AREA" ), QVariant::Double ) );
  fields.append( QgsField( QStringLiteral( "PERIM" ), QVariant::Double ) );

  QgsWkbTypes::Type outputType = QgsWkbTypes::Polygon;
  QgsCoordinateReferenceSystem crs = layer->crs();

  QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), fields, outputType, crs );
  QgsFeature currentFeature;
  QgsGeometry dissolveGeometry; //dissolve geometry
  QMultiMap<QString, QgsFeatureId> map;

  if ( onlySelectedFeatures )
  {
    //use QgsVectorLayer::featureAtId
    const QgsFeatureIds selection = layer->selectedFeaturesIds();
    QgsFeatureIds::const_iterator it = selection.constBegin();
    for ( ; it != selection.constEnd(); ++it )
    {
#if 0
      if ( p )
      {
        p->setValue( processedFeatures );
      }
      if ( p && p->wasCanceled() )
      {
        // break; // it may be better to do something else here?
        return false;
      }
#endif
      if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( currentFeature ) )
      {
        continue;
      }
      map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
    }
  }
  else
  {
    QgsFeatureIterator fit = layer->getFeatures();
    while ( fit.nextFeature( currentFeature ) )
    {
#if 0
      if ( p )
      {
        p->setValue( processedFeatures );
      }
      if ( p && p->wasCanceled() )
      {
        // break; // it may be better to do something else here?
        return false;
      }
#endif
      map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
    }
  }

  QMultiMap<QString, QgsFeatureId>::const_iterator jt = map.constBegin();
  while ( jt != map.constEnd() )
  {
    QString currentKey = jt.key();
    int processedFeatures = 0;
    //take only selection
    if ( onlySelectedFeatures )
    {
      //use QgsVectorLayer::featureAtId
      const QgsFeatureIds selection = layer->selectedFeaturesIds();
      if ( p )
      {
        p->setMaximum( selection.size() );
      }
      processedFeatures = 0;
      while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
      {
        if ( p && p->wasCanceled() )
        {
          break;
        }
        if ( selection.contains( jt.value() ) )
        {
          if ( p )
          {
            p->setValue( processedFeatures );
          }
          if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( jt.value() ) ).nextFeature( currentFeature ) )
          {
            continue;
          }
          convexFeature( currentFeature, processedFeatures, dissolveGeometry );
          ++processedFeatures;
        }
        ++jt;
      }
      QList<double> values;
      if ( dissolveGeometry.isEmpty() )
      {
        QgsDebugMsg( "no dissolved geometry - should not happen" );
        return false;
      }
      dissolveGeometry = dissolveGeometry.convexHull();
      values = simpleMeasure( dissolveGeometry );
      QgsAttributes attributes( 3 );
      attributes[0] = QVariant( currentKey );
      attributes[1] = values.at( 0 );
      attributes[2] = values.at( 1 );
      QgsFeature dissolveFeature;
      dissolveFeature.setAttributes( attributes );
      dissolveFeature.setGeometry( dissolveGeometry );
      vWriter.addFeature( dissolveFeature );
    }
    //take all features
    else
    {
      int featureCount = layer->featureCount();
      if ( p )
      {
        p->setMaximum( featureCount );
      }
      processedFeatures = 0;
      while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
      {
        if ( p )
        {
          p->setValue( processedFeatures );
        }

        if ( p && p->wasCanceled() )
        {
          break;
        }
        if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( jt.value() ) ).nextFeature( currentFeature ) )
        {
          continue;
        }
        convexFeature( currentFeature, processedFeatures, dissolveGeometry );
        ++processedFeatures;
        ++jt;
      }
      QList<double> values;
      if ( dissolveGeometry.isEmpty() )
      {
        QgsDebugMsg( "no dissolved geometry - should not happen" );
        return false;
      }
      dissolveGeometry = dissolveGeometry.convexHull();
      // values = simpleMeasure( tmpGeometry );
      values = simpleMeasure( dissolveGeometry );
      QgsAttributes attributes;
      attributes[0] = QVariant( currentKey );
      attributes[1] = QVariant( values[ 0 ] );
      attributes[2] = QVariant( values[ 1 ] );
      QgsFeature dissolveFeature;
      dissolveFeature.setAttributes( attributes );
      dissolveFeature.setGeometry( dissolveGeometry );
      vWriter.addFeature( dissolveFeature );
    }
  }
  return true;
}
void CalculateTaskScore::run()
{

    qDebug() << "CalculateTaskScore: Starting new thread";

    ConfigParser settings;
    QDateTime started = QDateTime::currentDateTime();
    ctemplate::TemplateDictionary dict("user_task_score");
    db = MySQLHandler::getInstance();
    QMultiMap<int, LCCode> users = UserDao::getUserNativeLCCodes(db);
    QList<QSharedPointer<Task> > tasks = this->getTasks();  //Must use custom function to check message for task id

    QMultiMap<int, LCCode> userSecondaryLanguages = UserDao::getUserLCCodes(db);
    QMultiMap<int, int> userTags = UserDao::getUserTagIds(db);
    QMultiMap<int, int> taskTags = TaskDao::getTaskTagIds(db);

    if(users.count() > 0) {
        for(QMultiMap<int, LCCode>::ConstIterator usersIter = users.constBegin(); usersIter != users.constEnd(); ++usersIter) {
            if(tasks.length() > 0) {
                const LCCode userNativeLCCode = users.value(usersIter.key());
                QList<TaskScore> taskScores;
                foreach(QSharedPointer<Task> task, tasks) {
                    int score = 0;

                    Locale taskSourceLocale = task->sourcelocale();

                    if(userNativeLCCode.first == taskSourceLocale.languagecode()) {
                        score += 750;
                        if(userNativeLCCode.second == taskSourceLocale.countrycode()) {
                            score += 75;
                        }
                    }

                    Locale taskTargetLocale = task->targetlocale();

                    if(userNativeLCCode.first == taskTargetLocale.languagecode()) {
                        score += 1000;
                        if(userNativeLCCode.second == taskTargetLocale.countrycode()) {
                            score += 100;
                        }
                    }

                    if(userSecondaryLanguages.contains(usersIter.key())) {
                        const QList<LCCode> lcCodes = userSecondaryLanguages.values(usersIter.key());
                        if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), LidMatch(taskSourceLocale.languagecode()))) {
                            score += 500;
                            if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), CidMatch(taskSourceLocale.countrycode())) ) {
                                score += 50;
                            }
                        }
                        if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), LidMatch(taskTargetLocale.languagecode()))) {
                            score += 500;
                            if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), CidMatch(taskTargetLocale.countrycode())) ) {
                                score += 50;
                            }
                        }
                    }

                    if(userTags.contains(usersIter.key()) && taskTags.contains(task->id())) {
                        int increment_value = 250;
                        QList<int> userTagIds = userTags.values(usersIter.key());
                        QList<int> userTaskTagIds = taskTags.values(task->id());

                        foreach(int userTagId, userTagIds) {
                            if(userTaskTagIds.contains(userTagId)) {
                                    score += increment_value;
                                    increment_value *= 0.75;
                            }
                        }
                    }

                    QDateTime created_time = QDateTime::fromString(
                                            QString::fromStdString(task->createdtime()), Qt::ISODate);
                    //increase score by one per day since created time
                    score += created_time.daysTo(QDateTime::currentDateTime());
                    taskScores.append(TaskScore(task->id(), score));
                }

                    this->saveUserTaskScore(usersIter.key(),taskScores);

            } else {
예제 #6
0
void OutputPaneManager::init()
{
    ActionManager *am = Core::ICore::instance()->actionManager();
    ActionContainer *mwindow = am->actionContainer(Constants::M_WINDOW);
    const Context globalcontext(Core::Constants::C_GLOBAL);

    // Window->Output Panes
    ActionContainer *mpanes = am->createMenu(Constants::M_WINDOW_PANES);
    mwindow->addMenu(mpanes, Constants::G_WINDOW_PANES);
    mpanes->menu()->setTitle(tr("Output &Panes"));
    mpanes->appendGroup("Coreplugin.OutputPane.ActionsGroup");
    mpanes->appendGroup("Coreplugin.OutputPane.PanesGroup");

    Core::Command *cmd;

    cmd = am->registerAction(m_clearAction, "Coreplugin.OutputPane.clear", globalcontext);
    m_clearButton->setDefaultAction(cmd->action());
    mpanes->addAction(cmd, "Coreplugin.OutputPane.ActionsGroup");

    cmd = am->registerAction(m_prevAction, "Coreplugin.OutputPane.previtem", globalcontext);
    cmd->setDefaultKeySequence(QKeySequence("Shift+F6"));
    m_prevToolButton->setDefaultAction(cmd->action());
    mpanes->addAction(cmd, "Coreplugin.OutputPane.ActionsGroup");

    cmd = am->registerAction(m_nextAction, "Coreplugin.OutputPane.nextitem", globalcontext);
    m_nextToolButton->setDefaultAction(cmd->action());
    cmd->setDefaultKeySequence(QKeySequence("F6"));
    mpanes->addAction(cmd, "Coreplugin.OutputPane.ActionsGroup");

    cmd = am->registerAction(m_minMaxAction, "Coreplugin.OutputPane.minmax", globalcontext);
#ifdef Q_WS_MAC
    cmd->setDefaultKeySequence(QKeySequence("Ctrl+9"));
#else
    cmd->setDefaultKeySequence(QKeySequence("Alt+9"));
#endif
    cmd->setAttribute(Command::CA_UpdateText);
    cmd->setAttribute(Command::CA_UpdateIcon);
    mpanes->addAction(cmd, "Coreplugin.OutputPane.ActionsGroup");
    connect(m_minMaxAction, SIGNAL(triggered()), this, SLOT(slotMinMax()));
    m_minMaxButton->setDefaultAction(cmd->action());

    QAction *sep = new QAction(this);
    sep->setSeparator(true);
    cmd = am->registerAction(sep, "Coreplugin.OutputPane.Sep", globalcontext);
    mpanes->addAction(cmd, "Coreplugin.OutputPane.ActionsGroup");

    QList<IOutputPane*> panes = ExtensionSystem::PluginManager::instance()
        ->getObjects<IOutputPane>();
    QMultiMap<int, IOutputPane*> sorted;
    foreach (IOutputPane* outPane, panes)
        sorted.insertMulti(outPane->priorityInStatusBar(), outPane);

    QMultiMap<int, IOutputPane*>::const_iterator it, begin;
    begin = sorted.constBegin();
    it = sorted.constEnd();
    int shortcutNumber = 1;
    while (it != begin) {
        --it;
        IOutputPane* outPane = it.value();
        const int idx = m_outputWidgetPane->addWidget(outPane->outputWidget(this));

        m_pageMap.insert(idx, outPane);
        connect(outPane, SIGNAL(showPage(bool,bool)), this, SLOT(showPage(bool,bool)));
        connect(outPane, SIGNAL(hidePage()), this, SLOT(slotHide()));
        connect(outPane, SIGNAL(togglePage(bool)), this, SLOT(togglePage(bool)));
        connect(outPane, SIGNAL(navigateStateUpdate()), this, SLOT(updateNavigateState()));

        QWidget *toolButtonsContainer = new QWidget(m_opToolBarWidgets);
        QHBoxLayout *toolButtonsLayout = new QHBoxLayout;
        toolButtonsLayout->setMargin(0);
        toolButtonsLayout->setSpacing(0);
        foreach (QWidget *toolButton, outPane->toolBarWidgets())
            toolButtonsLayout->addWidget(toolButton);
        toolButtonsLayout->addStretch(5);
        toolButtonsContainer->setLayout(toolButtonsLayout);

        m_opToolBarWidgets->addWidget(toolButtonsContainer);

        QString actionId = QString("QtCreator.Pane.%1").arg(outPane->displayName().simplified());
        actionId.remove(QLatin1Char(' '));
        QAction *action = new QAction(outPane->displayName(), this);

        Command *cmd = am->registerAction(action, Id(actionId), Context(Constants::C_GLOBAL));

        mpanes->addAction(cmd, "Coreplugin.OutputPane.PanesGroup");
        m_actions.insert(cmd->action(), idx);

        if (outPane->priorityInStatusBar() != -1) {
            cmd->setDefaultKeySequence(QKeySequence(paneShortCut(shortcutNumber)));
            QToolButton *button = new OutputPaneToggleButton(shortcutNumber, outPane->displayName(),
                                                             cmd->action());
            ++shortcutNumber;
            m_buttonsWidget->layout()->addWidget(button);
            connect(button, SIGNAL(clicked()), this, SLOT(buttonTriggered()));
            m_buttons.insert(idx, button);
        }

        // Now add the entry to the combobox, since the first item we add sets the currentIndex, thus we need to be set up for that
        m_widgetComboBox->addItem(outPane->displayName(), idx);

        connect(cmd->action(), SIGNAL(triggered()), this, SLOT(shortcutTriggered()));
    }

    changePage();
}
예제 #7
0
int main( int argc, char * argv[] )
{
#ifndef _MSC_VER
  qInstallMsgHandler( dummyMessageHandler );
#endif

  QString optionsPath = getenv( "QGIS_OPTIONS_PATH" );
  if ( !optionsPath.isEmpty() )
  {
    QgsDebugMsg( "Options PATH: " + optionsPath );
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionsPath );
  }

  QgsApplication qgsapp( argc, argv, getenv( "DISPLAY" ) );

  QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
  QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
  QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME );

  //Default prefix path may be altered by environment variable
  QgsApplication::init();
#if !defined(Q_OS_WIN)
  // init QGIS's paths - true means that all path will be inited from prefix
  QgsApplication::setPrefixPath( CMAKE_INSTALL_PREFIX, TRUE );
#endif

#if defined(SERVER_SKIP_ECW)
  QgsDebugMsg( "Skipping GDAL ECW drivers in server." );
  QgsApplication::skipGdalDriver( "ECW" );
  QgsApplication::skipGdalDriver( "JP2ECW" );
#endif

  setupNetworkAccessManager();
  QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );

  // Instantiate the plugin directory so that providers are loaded
  QgsProviderRegistry::instance( QgsApplication::pluginPath() );
  QgsDebugMsg( "Prefix  PATH: " + QgsApplication::prefixPath() );
  QgsDebugMsg( "Plugin  PATH: " + QgsApplication::pluginPath() );
  QgsDebugMsg( "PkgData PATH: " + QgsApplication::pkgDataPath() );
  QgsDebugMsg( "User DB PATH: " + QgsApplication::qgisUserDbFilePath() );
  QgsDebugMsg( "SVG PATHS: " + QgsApplication::svgPaths().join( ":" ) );

  QgsApplication::createDB(); //init qgis.db (e.g. necessary for user crs)

  QString defaultConfigFilePath;
  QFileInfo projectFileInfo = defaultProjectFile(); //try to find a .qgs file in the server directory
  if ( projectFileInfo.exists() )
  {
    defaultConfigFilePath = projectFileInfo.absoluteFilePath();
    QgsDebugMsg( "Using default project file: " + defaultConfigFilePath );
  }
  else
  {
    QFileInfo adminSLDFileInfo = defaultAdminSLD();
    if ( adminSLDFileInfo.exists() )
    {
      defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
    }
  }

  //create cache for capabilities XML
  QgsCapabilitiesCache capabilitiesCache;

  //creating QgsMapRenderer is expensive (access to srs.db), so we do it here before the fcgi loop
  QScopedPointer< QgsMapRenderer > theMapRenderer( new QgsMapRenderer );
  theMapRenderer->setLabelingEngine( new QgsPalLabeling() );

#ifdef QGSMSDEBUG
  QgsFontUtils::loadStandardTestFonts( QStringList() << "Roman" << "Bold" );
#endif

  int logLevel = QgsServerLogger::instance()->logLevel();
  QTime time; //used for measuring request time if loglevel < 1

#ifdef HAVE_SERVER_PYTHON_PLUGINS
  // Create the interface
  QgsServerInterfaceImpl serverIface( &capabilitiesCache );
  // Init plugins
  if ( ! QgsServerPlugins::initPlugins( &serverIface ) )
  {
    QgsMessageLog::logMessage( "No server python plugins are available", "Server", QgsMessageLog::INFO );
  }
  else
  {
    QgsMessageLog::logMessage( "Server python plugins loaded", "Server", QgsMessageLog::INFO );
  }
  // Store plugin filters for faster access
  QMultiMap<int, QgsServerFilter*> pluginFilters = serverIface.filters();
#endif

  QgsEditorWidgetRegistry::initEditors();

  while ( fcgi_accept() >= 0 )
  {
    QgsMapLayerRegistry::instance()->removeAllMapLayers();
    qgsapp.processEvents();

    if ( logLevel < 1 )
    {
      time.start();
      printRequestInfos();
    }

    //Request handler
    QScopedPointer<QgsRequestHandler> theRequestHandler( createRequestHandler() );

    try
    {
      // TODO: split parse input into plain parse and processing from specific services
      theRequestHandler->parseInput();
    }
    catch ( QgsMapServiceException& e )
    {
      QgsMessageLog::logMessage( "Parse input exception: " + e.message(), "Server", QgsMessageLog::CRITICAL );
      theRequestHandler->setServiceException( e );
    }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
    // Set the request handler into the interface for plugins to manipulate it
    serverIface.setRequestHandler( theRequestHandler.data() );
    // Iterate filters and call their requestReady() method
    QgsServerFiltersMap::const_iterator filtersIterator;
    for ( filtersIterator = pluginFilters.constBegin(); filtersIterator != pluginFilters.constEnd(); ++filtersIterator )
    {
      filtersIterator.value()->requestReady();
    }

    //Pass the filters to the requestHandler, this is needed for the following reasons:
    // 1. allow core services to access plugin filters and implement thir own plugin hooks
    // 2. allow requestHandler to call sendResponse plugin hook

    //TODO: implement this in the requestHandler ctor (far easier if we will get rid of
    //      HAVE_SERVER_PYTHON_PLUGINS
    theRequestHandler->setPluginFilters( pluginFilters );
#endif

    // Copy the parameters map
    QMap<QString, QString> parameterMap( theRequestHandler->parameterMap() );

    printRequestParameters( parameterMap, logLevel );
    QMap<QString, QString>::const_iterator paramIt;
    //Config file path
    QString configFilePath = configPath( defaultConfigFilePath, parameterMap );
    //Service parameter
    QString serviceString = theRequestHandler->parameter( "SERVICE" );

    if ( serviceString.isEmpty() )
    {
      // SERVICE not mandatory for WMS 1.3.0 GetMap & GetFeatureInfo
      QString requestString = theRequestHandler->parameter( "REQUEST" );
      if ( requestString == "GetMap" || requestString == "GetFeatureInfo" )
      {
        serviceString = "WMS";
      }
    }

    // Enter core services main switch
    if ( !theRequestHandler->exceptionRaised() )
    {
      if ( serviceString == "WCS" )
      {
        QgsWCSProjectParser* p = QgsConfigCache::instance()->wcsConfiguration( configFilePath );
        if ( !p )
        {
          theRequestHandler->setServiceException( QgsMapServiceException( "Project file error", "Error reading the project file" ) );
        }
        else
        {
          QgsWCSServer wcsServer( configFilePath, parameterMap, p, theRequestHandler.data() );
          wcsServer.executeRequest();
        }
      }
      else if ( serviceString == "WFS" )
      {
        QgsWFSProjectParser* p = QgsConfigCache::instance()->wfsConfiguration( configFilePath );
        if ( !p )
        {
          theRequestHandler->setServiceException( QgsMapServiceException( "Project file error", "Error reading the project file" ) );
        }
        else
        {
          QgsWFSServer wfsServer( configFilePath, parameterMap, p, theRequestHandler.data() );
          wfsServer.executeRequest();
        }
      }
      else if ( serviceString == "WMS" )
      {
        QgsWMSConfigParser* p = QgsConfigCache::instance()->wmsConfiguration( configFilePath, parameterMap );
        if ( !p )
        {
          theRequestHandler->setServiceException( QgsMapServiceException( "WMS configuration error", "There was an error reading the project file or the SLD configuration" ) );
        }
        else
        {
          QgsWMSServer wmsServer( configFilePath, parameterMap, p, theRequestHandler.data(), theMapRenderer.data(), &capabilitiesCache );
          wmsServer.executeRequest();
        }
      }
      else
      {
        theRequestHandler->setServiceException( QgsMapServiceException( "Service configuration error", "Service unknown or unsupported" ) );
      } // end switch
    } // end if not exception raised

#ifdef HAVE_SERVER_PYTHON_PLUGINS
    // Iterate filters and call their responseComplete() method
    for ( filtersIterator = pluginFilters.constBegin(); filtersIterator != pluginFilters.constEnd(); ++filtersIterator )
    {
      filtersIterator.value()->responseComplete();
    }
#endif
    theRequestHandler->sendResponse();

    if ( logLevel < 1 )
    {
      QgsMessageLog::logMessage( "Request finished in " + QString::number( time.elapsed() ) + " ms", "Server", QgsMessageLog::INFO );
    }
  }
  return 0;
}
/*!
    \internal

    Returns a lazily-initialized singleton. Ownership is granted to the
    QPlatformPrinterSupportPlugin, which is never unloaded or destroyed until
    application exit, i.e. you can expect this pointer to always be valid and
    multiple calls to this function will always return the same pointer.
*/
QPlatformPrinterSupport *QPlatformPrinterSupportPlugin::get()
{
    if (!printerSupport) {
        const QMultiMap<int, QString> keyMap = loader()->keyMap();
        if (!keyMap.isEmpty())
            printerSupport = qLoadPlugin<QPlatformPrinterSupport, QPlatformPrinterSupportPlugin>(loader(), keyMap.constBegin().value());
        if (printerSupport)
            qAddPostRoutine(cleanupPrinterSupport);
    }
    return printerSupport;
}
예제 #9
0
void
FormMain::folderChanged( QTreeWidgetItem * current, QTreeWidgetItem * )
{
	editInfo->clear();

	if ( ! current )
		return;

	const int folder_id = current->data( 0, Qt::UserRole ).toInt();

	QString text("Folder: ");

	QSqlQuery q;

	// self
	q.prepare("SELECT "
			"name, "
			"path, "
			"size "
		"FROM "
			"folders "
		"WHERE "
			"id = :id ");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		if ( q.first() )
			text += q.value( 0 ).toString() + "<BR>" +
				"Path: " + q.value( 1 ).toString() + "<BR>" +
				"Size: " + prettyPrint( q.value( 2 ).toLongLong() ) + "<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	// count of folders
	int folderCount = 0;
	countFolders( folder_id, folderCount );

	// count of types
	int typeCount = 0;
	QHash< QString, int > types;
	countTypes( folder_id, types, typeCount );

	// ordering
	QMultiMap< int, QString > typesMap;
	QHash< QString, int >::const_iterator h = types.constBegin();

	while ( h != types.constEnd() ) {
		typesMap.insert( h.value(), h.key() );
		++h;
	}

	// percent of folders
	text += tr("folders: %1 (%2%)<BR>")
		.arg( folderCount )
		.arg( folderCount / ( qreal )( folderCount + typeCount ) * 100., 0, 'f', 1 );

	// percents of files

	chart->clear();

	if ( typesMap.count() > 0 ) {
		QMultiMap< int, QString >::const_iterator mm = typesMap.constEnd();

		do {
			--mm;

			const qreal percent = mm.key() / ( qreal )( folderCount + typeCount ) * 100;

			text += tr("%1: %2 (%3%)<BR>")
				.arg( mm.value() )
				.arg( mm.key() )
				.arg( percent, 0, 'f', 1 );

			chart->addPiece( percent, mm.value() );

		} while ( mm != typesMap.constBegin() );
	}

	text += QString( 50, '-' ) + "<BR>";		// horizontal line -------

	// folders
	text += "<BR><B>folders:</B><BR>";

	q.prepare("SELECT "
			"name, "
			"size "
		"FROM "
			"folders "
		"WHERE "
			"parent_id = :id "
		"ORDER BY "
			"size DESC");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		while ( q.next() )
			text += q.value( 0 ).toString() +
				" (" + prettyPrint( q.value( 1 ).toLongLong() ) + ")<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	// files
	text += "<BR><B>files:</B><BR>";

	q.prepare("SELECT "
			"name, "
			"size "
		"FROM "
			"files "
		"WHERE "
			"folders_id = :id "
		"ORDER BY "
			"size DESC");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		while ( q.next() )
			text += q.value( 0 ).toString() +
				" (" + prettyPrint( q.value( 1 ).toLongLong() ) + ")<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	editInfo->setHtml( text );
}
NotifyKindOptionsWidget::NotifyKindOptionsWidget(INotifications *ANotifications, QWidget *AParent) : QWidget(AParent)
{
    FNotifications = ANotifications;

    tbwNotifies = new QTableWidget(this);
    tbwNotifies->setWordWrap(true);
    tbwNotifies->verticalHeader()->setVisible(false);
    tbwNotifies->horizontalHeader()->setHighlightSections(false);
    tbwNotifies->setSelectionMode(QTableWidget::NoSelection);
    connect(tbwNotifies,SIGNAL(itemChanged(QTableWidgetItem *)),SIGNAL(modified()));

    tbwNotifies->setColumnCount(NTC__COUNT);
    tbwNotifies->setHorizontalHeaderLabels(QStringList() << tr("Event") << "" << "" << "" << "" );
    tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_TYPE,QHeaderView::Stretch);

    tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_SOUND,QHeaderView::ResizeToContents);
    tbwNotifies->horizontalHeaderItem(NTC_SOUND)->setToolTip(tr("Play sound at the notification"));
    tbwNotifies->horizontalHeaderItem(NTC_SOUND)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_SOUNDPLAY));

    tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_POPUP,QHeaderView::ResizeToContents);
    tbwNotifies->horizontalHeaderItem(NTC_POPUP)->setToolTip(tr("Display a notification in popup window"));
    tbwNotifies->horizontalHeaderItem(NTC_POPUP)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_PUPUPWINDOW));

    tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_MINIMIZED,QHeaderView::ResizeToContents);
    tbwNotifies->horizontalHeaderItem(NTC_MINIMIZED)->setToolTip(tr("Show the corresponding window minimized in the taskbar"));
    tbwNotifies->horizontalHeaderItem(NTC_MINIMIZED)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_SHOWMINIMIZED));

    tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_TRAY,QHeaderView::ResizeToContents);
    tbwNotifies->horizontalHeaderItem(NTC_TRAY)->setToolTip(tr("Display a notification icon in the system tray"));
    tbwNotifies->horizontalHeaderItem(NTC_TRAY)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_TRAYICON));

    QVBoxLayout *vblLayout = new QVBoxLayout(this);
    vblLayout->addWidget(tbwNotifies);
    vblLayout->setMargin(0);

    QMultiMap<int, NotificationType> orderedTypes;
    ushort visibleKinds = INotification::PopupWindow|INotification::TrayNotify|INotification::SoundPlay|INotification::ShowMinimized;
    foreach(const QString &typeId, FNotifications->notificationTypes())
    {
        NotificationType notifyType = FNotifications->notificationType(typeId);
        if (!notifyType.title.isEmpty() && (notifyType.kindMask & visibleKinds)>0)
        {
            notifyType.typeId = typeId;
            orderedTypes.insertMulti(notifyType.order,notifyType);
        }
    }

    for (QMultiMap<int, NotificationType>::const_iterator it=orderedTypes.constBegin(); it!=orderedTypes.constEnd(); ++it)
    {
        int row = tbwNotifies->rowCount();
        tbwNotifies->setRowCount(row+1);

        QTableWidgetItem *type = new QTableWidgetItem(it->icon,it->title);
        type->setData(NTR_TYPE, it->typeId);
        type->setFlags(Qt::ItemIsEnabled);
        tbwNotifies->setItem(row,NTC_TYPE,type);

        QTableWidgetItem *sound = new QTableWidgetItem();
        sound->setData(NTR_KIND, INotification::SoundPlay);
        if (it->kindMask & INotification::SoundPlay)
            sound->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
        else
            sound->setFlags(Qt::ItemIsUserCheckable);
        sound->setCheckState(Qt::Unchecked);
        tbwNotifies->setItem(row,NTC_SOUND,sound);

        QTableWidgetItem *popup = new QTableWidgetItem();
        popup->setData(NTR_KIND, INotification::PopupWindow);
        if (it->kindMask & INotification::PopupWindow)
            popup->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
        else
            popup->setFlags(Qt::ItemIsUserCheckable);
        popup->setCheckState(Qt::Unchecked);
        tbwNotifies->setItem(row,NTC_POPUP,popup);

        QTableWidgetItem *minimized = new QTableWidgetItem();
        minimized->setData(NTR_KIND, INotification::ShowMinimized);
        if (it->kindMask & INotification::ShowMinimized)
            minimized->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
        else
            minimized->setFlags(Qt::ItemIsUserCheckable);
        minimized->setCheckState(Qt::Unchecked);
        tbwNotifies->setItem(row,NTC_MINIMIZED,minimized);

        tbwNotifies->verticalHeader()->SETRESIZEMODE(row,QHeaderView::ResizeToContents);
        QTableWidgetItem *tray = new QTableWidgetItem();
        tray->setData(NTR_KIND, INotification::TrayNotify);
        if (it->kindMask & INotification::TrayNotify)
            tray->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
        else
            tray->setFlags(Qt::ItemIsUserCheckable);
        tray->setCheckState(Qt::Unchecked);
        tbwNotifies->setItem(row,NTC_TRAY,tray);

        tbwNotifies->verticalHeader()->SETRESIZEMODE(row,QHeaderView::ResizeToContents);
    }

    reset();
}
예제 #11
0
void Playlist::shuffleTracks(MusicPlayer::ShuffleMode shuffleMode)
{
    m_shuffledSongs.clear();

    switch (shuffleMode)
    {
        case MusicPlayer::SHUFFLE_RANDOM:
        {
            QMultiMap<int, MusicMetadata*> songMap;

            SongList::const_iterator it = m_songs.begin();
            for (; it != m_songs.end(); ++it)
            {
                songMap.insert(rand(), *it);
            }

            QMultiMap<int, MusicMetadata*>::const_iterator i = songMap.constBegin();
            while (i != songMap.constEnd())
            {
                m_shuffledSongs.append(i.value());
                ++i;
            }

            break;
        }

        case MusicPlayer::SHUFFLE_INTELLIGENT:
        {
            int RatingWeight = 2;
            int PlayCountWeight = 2;
            int LastPlayWeight = 2;
            int RandomWeight = 2;
            m_parent->FillIntelliWeights(RatingWeight, PlayCountWeight,
                                         LastPlayWeight, RandomWeight);

            // compute max/min playcount,lastplay for this playlist
            int playcountMin = 0;
            int playcountMax = 0;
            double lastplayMin = 0.0;
            double lastplayMax = 0.0;

            uint idx = 0;
            SongList::const_iterator it = m_songs.begin();
            for (; it != m_songs.end(); ++it, ++idx)
            {
                if (!(*it)->isCDTrack())
                {
                    MusicMetadata *mdata = (*it);

                    if (0 == idx)
                    {
                        // first song
                        playcountMin = playcountMax = mdata->PlayCount();
                        lastplayMin = lastplayMax = mdata->LastPlay().toTime_t();
                    }
                    else
                    {
                        if (mdata->PlayCount() < playcountMin)
                            playcountMin = mdata->PlayCount();
                        else if (mdata->PlayCount() > playcountMax)
                            playcountMax = mdata->PlayCount();

                        if (mdata->LastPlay().toTime_t() < lastplayMin)
                            lastplayMin = mdata->LastPlay().toTime_t();
                        else if (mdata->LastPlay().toTime_t() > lastplayMax)
                            lastplayMax = mdata->LastPlay().toTime_t();
                    }
                }
            }

            // next we compute all the weights
            std::map<int,double> weights;
            std::map<int,int> ratings;
            std::map<int,int> ratingCounts;
            int TotalWeight = RatingWeight + PlayCountWeight + LastPlayWeight;
            for (int trackItI = 0; trackItI < m_songs.size(); ++trackItI)
            {
                MusicMetadata *mdata = m_songs[trackItI];
                if (!mdata->isCDTrack())
                {
                    int rating = mdata->Rating();
                    int playcount = mdata->PlayCount();
                    double lastplaydbl = mdata->LastPlay().toTime_t();
                    double ratingValue = (double)(rating) / 10;
                    double playcountValue, lastplayValue;

                    if (playcountMax == playcountMin)
                        playcountValue = 0;
                    else
                        playcountValue = ((playcountMin - (double)playcount) / (playcountMax - playcountMin) + 1);

                    if (lastplayMax == lastplayMin)
                        lastplayValue = 0;
                    else
                        lastplayValue = ((lastplayMin - lastplaydbl) / (lastplayMax - lastplayMin) + 1);

                    double weight = (RatingWeight * ratingValue +
                                        PlayCountWeight * playcountValue +
                                        LastPlayWeight * lastplayValue) / TotalWeight;
                    weights[mdata->ID()] = weight;
                    ratings[mdata->ID()] = rating;
                    ++ratingCounts[rating];
                }
            }

            // then we divide weights with the number of songs in the rating class
            // (more songs in a class ==> lower weight, without affecting other classes)
            double totalWeights = 0;
            std::map<int,double>::iterator weightsIt, weightsEnd = weights.end();
            for (weightsIt = weights.begin() ; weightsIt != weightsEnd ; ++weightsIt)
            {
                weightsIt->second /= ratingCounts[ratings[weightsIt->first]];
                totalWeights += weightsIt->second;
            }

            // then we get a random order, balanced with relative weights of remaining songs
            std::map<int,uint32_t> order;
            uint32_t orderCpt = 1;
            std::map<int,double>::iterator weightIt, weightEnd;
            while (!weights.empty())
            {
                double hit = totalWeights * (double)rand() / (double)RAND_MAX;
                weightEnd = weights.end();
                weightIt = weights.begin();
                double pos = 0;
                while (weightIt != weightEnd)
                {
                    pos += weightIt->second;
                    if (pos >= hit)
                        break;
                    ++weightIt;
                }

                // FIXME If we don't exit here then we'll segfault, but it
                //       probably won't give us the desired randomisation
                //       either - There seems to be a flaw in this code, we
                //       erase items from the map but never adjust
                //       'totalWeights' so at a point 'pos' will never be
                //       greater or equal to 'hit' and we will always hit the
                //       end of the map
                if (weightIt == weightEnd)
                    break;

                order[weightIt->first] = orderCpt;
                totalWeights -= weightIt->second;
                weights.erase(weightIt);
                ++orderCpt;
            }

            // create a map of tracks sorted by the computed order
            QMultiMap<int, MusicMetadata*> songMap;
            it = m_songs.begin();
            for (; it != m_songs.end(); ++it)
                songMap.insert(order[(*it)->ID()], *it);

            // copy the shuffled tracks to the shuffled song list
            QMultiMap<int, MusicMetadata*>::const_iterator i = songMap.constBegin();
            while (i != songMap.constEnd())
            {
                m_shuffledSongs.append(i.value());
                ++i;
            }

            break;
        }

        case MusicPlayer::SHUFFLE_ALBUM:
        {
            // "intellegent/album" order

            typedef map<QString, uint32_t> AlbumMap;
            AlbumMap                       album_map;
            AlbumMap::iterator             Ialbum;
            QString                        album;

            // pre-fill the album-map with the album name.
            // This allows us to do album mode in album order
            SongList::const_iterator it = m_songs.begin();
            for (; it != m_songs.end(); ++it)
            {
                MusicMetadata *mdata = (*it);
                album = mdata->Album() + " ~ " + QString("%1").arg(mdata->getAlbumId());
                if ((Ialbum = album_map.find(album)) == album_map.end())
                    album_map.insert(AlbumMap::value_type(album, 0));
            }

            // populate the sort id into the album map
            uint32_t album_count = 1;
            for (Ialbum = album_map.begin(); Ialbum != album_map.end(); ++Ialbum)
            {
                Ialbum->second = album_count;
                album_count++;
            }

            // create a map of tracks sorted by the computed order
            QMultiMap<int, MusicMetadata*> songMap;
            it = m_songs.begin();
            for (; it != m_songs.end(); ++it)
            {
                uint32_t album_order;
                MusicMetadata *mdata = (*it);
                if (mdata)
                {
                    album = album = mdata->Album() + " ~ " + QString("%1").arg(mdata->getAlbumId());;
                    if ((Ialbum = album_map.find(album)) == album_map.end())
                    {
                        // we didn't find this album in the map,
                        // yet we pre-loaded them all. we are broken,
                        // but we just set the track order to 1, since there
                        // is no real point in reporting an error
                        album_order = 1;
                    }
                    else
                    {
                        album_order = Ialbum->second * 1000;
                    }
                    album_order += mdata->Track();

                    songMap.insert(album_order, *it);
                }
            }

            // copy the shuffled tracks to the shuffled song list
            QMultiMap<int, MusicMetadata*>::const_iterator i = songMap.constBegin();
            while (i != songMap.constEnd())
            {
                m_shuffledSongs.append(i.value());
                ++i;
            }

            break;
        }

        case MusicPlayer::SHUFFLE_ARTIST:
        {
            // "intellegent/album" order

            typedef map<QString, uint32_t> ArtistMap;
            ArtistMap                      artist_map;
            ArtistMap::iterator            Iartist;
            QString                        artist;

            // pre-fill the album-map with the album name.
            // This allows us to do artist mode in artist order
            SongList::const_iterator it = m_songs.begin();
            for (; it != m_songs.end(); ++it)
            {
                MusicMetadata *mdata = (*it);
                artist = mdata->Artist() + " ~ " + mdata->Title();
                if ((Iartist = artist_map.find(artist)) == artist_map.end())
                    artist_map.insert(ArtistMap::value_type(artist,0));
            }

            // populate the sort id into the artist map
            uint32_t artist_count = 1;
            for (Iartist = artist_map.begin(); Iartist != artist_map.end(); ++Iartist)
            {
                Iartist->second = artist_count;
                artist_count++;
            }

            // create a map of tracks sorted by the computed order
            QMultiMap<int, MusicMetadata*> songMap;
            it = m_songs.begin();
            for (; it != m_songs.end(); ++it)
            {
                uint32_t artist_order;
                MusicMetadata *mdata = (*it);
                if (mdata)
                {
                    artist = mdata->Artist() + " ~ " + mdata->Title();
                    if ((Iartist = artist_map.find(artist)) == artist_map.end())
                    {
                        // we didn't find this artist in the map,
                        // yet we pre-loaded them all. we are broken,
                        // but we just set the track order to 1, since there
                        // is no real point in reporting an error
                        artist_order = 1;
                    }
                    else
                    {
                        artist_order = Iartist->second * 1000;
                    }
                    artist_order += mdata->Track();

                    songMap.insert(artist_order, *it);
                }
            }

            // copy the shuffled tracks to the shuffled song list
            QMultiMap<int, MusicMetadata*>::const_iterator i = songMap.constBegin();
            while (i != songMap.constEnd())
            {
                m_shuffledSongs.append(i.value());
                ++i;
            }

            break;
        }

        default:
        {
            // copy the raw song list to the shuffled track list
            SongList::const_iterator it = m_songs.begin();
            for (; it != m_songs.end(); ++it)
            {
                m_shuffledSongs.append(*it);
            }

            break;
        }
    }
}
예제 #12
0
QByteArray Token::signRequest(const QUrl& requestUrl, Token::AuthMethod authMethod, Token::HttpMethod method, const QMultiMap<QString, QString>& parameters) const
{
	QString timestamp;
	QString nonce;

	if (d->consumerKey == "test_token") { // Set known values for unit-testing
		timestamp = "1234567890";	//Feb 13, 2009, 23:31:30 GMT
		nonce = "ABCDEF";
	} else {
#if QT_VERSION >= 0x040700
		timestamp = QString::number(QDateTime::currentDateTimeUtc().toTime_t());
#else
		timestamp = QString::number(QDateTime::currentDateTime().toUTC().toTime_t());
#endif
		nonce = QString::number(qrand());
	}

	if (!requestUrl.isValid()) {
		qWarning() << "OAuth::Token: Invalid url. The request will probably be invalid";
	}

	// Step 1. Get all the oauth params for this request

	QMultiMap<QString, QString> oauthParams;

	oauthParams.insert("oauth_consumer_key", d->consumerKey);
    if(d->serviceType == "dbox")
        oauthParams.insert("oauth_signature_method", "PLAINTEXT");
    else
        oauthParams.insert("oauth_signature_method", "HMAC-SHA1");
	oauthParams.insert("oauth_timestamp", timestamp);
	oauthParams.insert("oauth_nonce", nonce);
	oauthParams.insert("oauth_version", "1.0");

	switch (d->tokenType) {
	case Token::InvalidToken:
		oauthParams.insert("oauth_callback", d->callbackUrl.toString());
		break;

	case Token::RequestToken:
		oauthParams.insert("oauth_token", d->oauthToken);
		oauthParams.insert("oauth_verifier", d->oauthVerifier);
		break;

	case Token::AccessToken:
		oauthParams.insert("oauth_token", d->oauthToken);
		break;
	}

	// Step 2. Take the parameters from the url, and add the oauth params to them

	QMultiMap<QString, QString> allParams = oauthParams;
	QList<QPair<QString, QString> > queryItems = requestUrl.queryItems();
	for(int i = 0; i < queryItems.count(); ++i) {
		allParams.insert(queryItems[i].first, queryItems[i].second);
	}

	allParams.unite(parameters);

	// Step 3. Calculate the signature from those params, and append the signature to the oauth params

	QString signature = generateSignature(requestUrl, allParams, method);
	oauthParams.insert("oauth_signature", signature);

	// Step 4. Concatenate all oauth params into one comma-separated string

	QByteArray authHeader;

	if (authMethod == Sasl) {
		authHeader = "GET ";
		authHeader.append(requestUrl.toString() + " ");
	} else {
		authHeader = "OAuth ";
	}

	QMultiMap<QString, QString>::const_iterator p = oauthParams.constBegin();
	while (p != oauthParams.constEnd()) {
		authHeader += QString("%1=\"%2\",").arg(p.key()).arg(encode(p.value()));
		++p;
	}
	authHeader.chop(1); // remove the last character (the trailing ",")

	return authHeader;
}