Development/Tutorials/Collaboration/Attica/Introduction: Difference between revisions

From KDE TechBase
(Mark for updating)
 
(13 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Template:I18n/Language Navigation Bar|Development/Tutorials/Collaboration/Attica/Introduction}}
 


{{TutorialBrowser|
{{TutorialBrowser|
Line 5: Line 5:
name=Attica Introduction|
name=Attica Introduction|
pre=[[Getting_Started|Getting started with KDE development]]|
pre=[[Getting_Started|Getting started with KDE development]]|
}}
}}  
 
{{Review|Port to KF5}}
 
== Overview ==
 
In this tutorial you learn how to use Attica to access the Open Collaboration Services in your application.
 
Our goal is to get a list of friends for any user registered on this site.
 
With Attica you can easily access services from providers such as [http://opendesktop.org openDesktop.org]. It implements the [http://www.freedesktop.org freedesktop.org] specification for the [http://www.freedesktop.org/wiki/Specifications/open-collaboration-services Open Collaboration Services API].


==Overview==
The code for this tutorial is also available in the kdeexamples module in [http://websvn.kde.org/trunk/KDE/kdeexamples/attica/ kde svn].  
In this tutorial you learn how to use Attica to access the Open Collaboration Services in your application.


Our goal is to get a list of friends for any user registered on this site.
== Providers ==


With Attica you can easily access services from providers such as [http://opendesktop.org openDesktop.org].
Attica supports multiple Open Collaboration Service (OCS) providers at the same time. Therefor the first thing to do is getting a ProviderManager and either asking it for a default provider (e.g. openDesktop.org for KDE) or setting a different provider by hand. Let's create a mainwindow class that loads the openDesktop.org provider. Make sure you have the KDE Plugin for Attica built, otherwise openDesktop.org will not be in the list of default providers.
It implements the [http://www.freedesktop.org freedesktop.org] specification for the [http://www.freedesktop.org/wiki/Specifications/open-collaboration-services Open Collaboration Services API].


==Providers==
=== Mainwindow ===
Attica supports multiple Open Collaboration Service (OCS) providers at the same time.
Therefor the first thing to do is getting a ProviderManager and either asking it for a default provider (e.g. openDesktop.org for KDE) or setting a different provider by hand.
Let's create a mainwindow class that loads the openDesktop.org provider.
Make sure you have the KDE Plugin for Attica built, otherwise openDesktop.org will not be in the list of default providers.


===Mainwindow===
To make setting up the tutorial as easy as possible, here is a complete KDE application. We start with the mainwindow and add things into it.  
To make setting up the tutorial as easy as possible, here is a complete KDE application. We start with the mainwindow and add things into it.
 
====mainwindow.h====
==== mainwindow.h ====
<code cppqt>
 
<syntaxhighlight lang="cpp-qt">
//mainwindow.h
//mainwindow.h
#ifndef MAINWINDOW_H
#ifndef MAINWINDOW_H
Line 32: Line 37:
#include <KLineEdit>
#include <KLineEdit>
#include <QLabel>
#include <QLabel>
 
#include <attica/providermanager.h>
#include <attica/providermanager.h>
#include <attica/provider.h>
#include <attica/provider.h>
 
class MainWindow : public KMainWindow
class MainWindow : public KMainWindow
{
{
     Q_OBJECT
     Q_OBJECT
 
public:
public:
     MainWindow(QWidget *parent=0);
     MainWindow(QWidget *parent=0);
 
public Q_SLOTS:
public Q_SLOTS:
     // Here we will get notified, when the provider is loaded
     // Here we will get notified, when the provider is loaded
     void providersChanged();
     void providersChanged();
 
private:
private:
     // ProviderManager is the class that lets us "create" providers
     // ProviderManager is the class that lets us "create" providers
Line 54: Line 59:
};
};
#endif
#endif
</code>
</syntaxhighlight>  


====mainwindow.cpp====
==== mainwindow.cpp ====
<code cppqt>
 
<syntaxhighlight lang="cpp-qt">
//mainwindow.cpp
//mainwindow.cpp
#include "mainwindow.h"
#include "mainwindow.h"
 
#include <KDebug>
#include <KDebug>
#include <QVBoxLayout>
#include <QVBoxLayout>
 
#include <attica/providermanager.h>
#include <attica/providermanager.h>
#include "simplepersonrequest.h"
#include "simplepersonrequest.h"
 
MainWindow::MainWindow(QWidget *parent) : KMainWindow(parent)
MainWindow::MainWindow(QWidget *parent) : KMainWindow(parent)
{
{
     // connect to get notified, when new Providers are loaded
     // connect to get notified, when new Providers are loaded
     connect(&m_manager, SIGNAL(providersChanged()), SLOT(providersChanged()));
     connect(&m_manager, SIGNAL(defaultProvidersLoaded()), SLOT(providersChanged()));
     // tell it to get the default Providers
     // tell it to get the default Providers
     m_manager.loadDefaultProviders();
     m_manager.loadDefaultProviders();
}
}
 
// called when a provider was loaded
// called when a provider was loaded
void MainWindow::providersChanged()
void MainWindow::providersChanged()
Line 94: Line 100:
}
}
#include "mainwindow.moc"
#include "mainwindow.moc"
</code>
</syntaxhighlight>  


Now we have a simple mainwindow with a tab widget. The real contents is still missing though. The first widget we'll add gives some information about a Person.
Now we have a simple mainwindow with a tab widget. The real contents is still missing though. The first widget we'll add gives some information about a Person.


==Person==
Note also that in this case the provider file for the OCS server residing at "https://api.opendesktop.org/v1/" is already loaded calling '''m_manager.loadDefaultProviders();'''. If you want to run your custom server you should first load your provider file and then select it using '''m_manager.providerByUrl()''' method.
Now that we have a Provider, we can ask it for information.
Here is a small example quoting only the code that changed:
As a first step, let's find out who I am. Entering any user nick into a KLineEdit will look up that Person.
 
[[File:tutorial_attica_person.png]]
<syntaxhighlight lang="cpp-qt">
Here is a class that subclasses QWidget and simply contains two labels that show the real name and city for a Person:
// [...]
====simplepersonrequest.h====
    connect(&m_manager, SIGNAL(defaultProvidersLoaded()), SLOT(providersChanged()));
<code cppqt>
    // load your custom provider file to ProviderManager list
  m_manager.addProviderFile(QUrl("http://example.com/providers.xml"));
}
 
void MainWindow::providersChanged()
{
    if (!m_manager.providers().isEmpty()) {
        // this will select and return your provider file using the url
        m_provider = m_manager.providerByUrl(QUrl("https://example.com/v1/"));
// [...]
</syntaxhighlight>
 
== Person ==
 
Now that we have a Provider, we can ask it for information. As a first step, let's find out who I am. Entering any user nick into a KLineEdit will look up that Person. [[Image:Tutorial attica person.png]] Here is a class that subclasses QWidget and simply contains two labels that show the real name and city for a Person. Since the Data has to be fetched from the server using a REST API, it is asynchronous. When the data arrived, we get notified by a signal.
 
==== simplepersonrequest.h ====
 
<syntaxhighlight lang="cpp-qt">
#ifndef SIMPLEPERSONREQUEST_H
#ifndef SIMPLEPERSONREQUEST_H
#define SIMPLEPERSONREQUEST_H
#define SIMPLEPERSONREQUEST_H
 
#include <QtGui/QLabel>
#include <QtGui/QLabel>
#include <KLineEdit>
#include <KLineEdit>
#include <attica/provider.h>
#include <attica/provider.h>
 
class SimplePersonRequest :public QWidget
class SimplePersonRequest :public QWidget
{
{
     Q_OBJECT
     Q_OBJECT
public:
public:
   
     SimplePersonRequest(Attica::Provider provider, QWidget* parent = 0);
     SimplePersonRequest(Attica::Provider provider, QWidget* parent = 0);
 
public Q_SLOTS:
public Q_SLOTS:
    // When the user entered a different nick name in the line edit and pressed enter.
     void nickChanged(const QString& nick);
     void nickChanged(const QString& nick);
    // The information has been loaded.
     void onPersonJobFinished( Attica::BaseJob *job );
     void onPersonJobFinished( Attica::BaseJob *job );
   
private:
private:
     KLineEdit* mNickNameLineEdit;
     KLineEdit* mNickNameLineEdit;
Line 130: Line 155:
     Attica::Provider m_provider;
     Attica::Provider m_provider;
};
};
#endif // SIMPLEPERSONREQUEST_H
</syntaxhighlight>


#endif // SIMPLEPERSONREQUEST_H
==== simplepersonrequest.cpp ====
</code>


====simplepersonrequest.cpp====
Now to the actual implementation of our Widget that shows information about a person: <syntaxhighlight lang="cpp-qt">
<code cppqt>
#include "simplepersonrequest.h"
#include "simplepersonrequest.h"
 
#include <KDebug>
#include <KDebug>
#include <QtGui/QBoxLayout>
#include <QtGui/QBoxLayout>
#include <QtGui/QSpacerItem>
#include <QtGui/QSpacerItem>
 
#include <attica/person.h>
#include <attica/person.h>
#include <attica/itemjob.h>
#include <attica/itemjob.h>
 
SimplePersonRequest::SimplePersonRequest(Attica::Provider provider, QWidget* parent)
SimplePersonRequest::SimplePersonRequest(Attica::Provider provider, QWidget* parent)
     : QWidget(parent)
     : QWidget(parent)
Line 150: Line 175:
{
{
     QVBoxLayout* layout = new QVBoxLayout(this);
     QVBoxLayout* layout = new QVBoxLayout(this);
   
     mNickNameLineEdit = new KLineEdit();
     mNickNameLineEdit = new KLineEdit();
     layout->addWidget(mNickNameLineEdit);
     layout->addWidget(mNickNameLineEdit);
 
     mNameLabel = new QLabel(this);
     mNameLabel = new QLabel(this);
     mNameLabel->setText("Name");
     mNameLabel->setText("Name");
     layout->addWidget(mNameLabel);
     layout->addWidget(mNameLabel);
 
     mLocationLabel = new QLabel(this);
     mLocationLabel = new QLabel(this);
     mLocationLabel->setText("Picture");
     mLocationLabel->setText("Location");
     layout->addWidget(mLocationLabel);
     layout->addWidget(mLocationLabel);
 
     mNick = "fregl";
     mNick = "fregl";
     mNickNameLineEdit->setText(mNick);
     mNickNameLineEdit->setText(mNick);
    // watch the LineEdit for changes
     connect(mNickNameLineEdit, SIGNAL(returnPressed(QString)), SLOT(nickChanged(QString)));
     connect(mNickNameLineEdit, SIGNAL(returnPressed(QString)), SLOT(nickChanged(QString)));
    // load the data
     nickChanged(mNick);
     nickChanged(mNick);
}
}
 
// The user pressed enter, try to get information about the nick name
void SimplePersonRequest::nickChanged(const QString& nick)
void SimplePersonRequest::nickChanged(const QString& nick)
{
{
     mNick = nick;
     mNick = nick;
    // ask the provider for a job that loads the person information:
     Attica::ItemJob<Attica::Person>* job = m_provider.requestPerson(mNick);
     Attica::ItemJob<Attica::Person>* job = m_provider.requestPerson(mNick);
    // connect that job
     connect(job, SIGNAL(finished(Attica::BaseJob*)), SLOT(onPersonJobFinished(Attica::BaseJob*)));
     connect(job, SIGNAL(finished(Attica::BaseJob*)), SLOT(onPersonJobFinished(Attica::BaseJob*)));
    // start the job
     job->start();
     job->start();
}
}
 
// New information has arrived
void SimplePersonRequest::onPersonJobFinished( Attica::BaseJob *job )
void SimplePersonRequest::onPersonJobFinished( Attica::BaseJob *job )
{
{
     kDebug() << "onJobFinished";
     kDebug() << "onJobFinished";
    // Get the information about the person: we need to turn the job into its proper sub class
     Attica::ItemJob<Attica::Person> *personJob = static_cast< Attica::ItemJob<Attica::Person> * >( job );
     Attica::ItemJob<Attica::Person> *personJob = static_cast< Attica::ItemJob<Attica::Person> * >( job );
    // check if the request actually worked
     if( personJob->metadata().error() == Attica::Metadata::NoError ) {
     if( personJob->metadata().error() == Attica::Metadata::NoError ) {
        // use the data to fill the labels
         Attica::Person p(personJob->result());
         Attica::Person p(personJob->result());
         mNameLabel->setText(p.firstName() + ' ' + p.lastName());
         mNameLabel->setText(p.firstName() + ' ' + p.lastName());
Line 188: Line 223:
     }
     }
}
}
#include "simplepersonrequest.moc"</syntaxhighlight>
== Compiling the example ==


#include "simplepersonrequest.moc"
The last thing missing is a small main.cpp and CMakeLists.txt to complete the example and make it compile:
</code>


==Compiling the example==
==== main.cpp ====
The last thing missing is a small main.cpp and CMakeLists.txt to complete the example and make it compile:


====main.cpp====
<syntaxhighlight lang="cpp-qt">
<code cppqt>
#include <KApplication>
#include <KApplication>
#include <KAboutData>
#include <KAboutData>
Line 203: Line 238:
   
   
#include "mainwindow.h"
#include "mainwindow.h"
 
int main (int argc, char *argv[])
int main (int argc, char *argv[])
{
{
Line 212: Line 247:
     ki18n("Copyright (c) 2009 Frederik Gladhorn") );
     ki18n("Copyright (c) 2009 Frederik Gladhorn") );
     KCmdLineArgs::init( argc, argv, &aboutData );
     KCmdLineArgs::init( argc, argv, &aboutData );
 
     KApplication app;
     KApplication app;
   
     MainWindow* window = new MainWindow();
     MainWindow* window = new MainWindow();
     window->show();
     window->show();
   
     return app.exec();
     return app.exec();
}
}</syntaxhighlight>  
</code>
 
====CMakeLists.txt====
==== CMakeLists.txt ====
<code>
 
<syntaxhighlight lang="text">
project (opencollaborationexample)
project (opencollaborationexample)


include_directories(${KDE4_INCLUDES}  ${ATTICA_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR})
find_package(KDE4 REQUIRED)
find_package(LibAttica REQUIRED)


include_directories(${KDE4_INCLUDES}  ${ATTICA_INCLUDE_DIRS}
    ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
set(opencollaborationexample_SRCS
set(opencollaborationexample_SRCS
     main.cpp
     main.cpp
Line 233: Line 273:
)
)


qt4_automoc(opencollaborationexample_SRCS)
kde4_add_executable(opencollaborationexample ${opencollaborationexample_SRCS})
kde4_add_executable(opencollaborationexample ${opencollaborationexample_SRCS})
target_link_libraries(opencollaborationexample  ${ATTICA_LIBRARIES} ${KDE4_KIO_LIBS}  ${KDE4_KDEUI_LIBS})
target_link_libraries(opencollaborationexample  ${LIBATTICA_LIBRARIES}
</code>
    ${KDE4_KIO_LIBS}  ${KDE4_KDEUI_LIBS})
</syntaxhighlight>

Latest revision as of 12:47, 31 May 2019


Attica Introduction
Tutorial Series   Attica
Previous   Getting started with KDE development
What's Next   n/a
Further Reading   n/a
Warning
This page needs a review and probably holds information that needs to be fixed.

Parts to be reviewed:

Port to KF5

Overview

In this tutorial you learn how to use Attica to access the Open Collaboration Services in your application.

Our goal is to get a list of friends for any user registered on this site.

With Attica you can easily access services from providers such as openDesktop.org. It implements the freedesktop.org specification for the Open Collaboration Services API.

The code for this tutorial is also available in the kdeexamples module in kde svn.

Providers

Attica supports multiple Open Collaboration Service (OCS) providers at the same time. Therefor the first thing to do is getting a ProviderManager and either asking it for a default provider (e.g. openDesktop.org for KDE) or setting a different provider by hand. Let's create a mainwindow class that loads the openDesktop.org provider. Make sure you have the KDE Plugin for Attica built, otherwise openDesktop.org will not be in the list of default providers.

Mainwindow

To make setting up the tutorial as easy as possible, here is a complete KDE application. We start with the mainwindow and add things into it.

mainwindow.h

//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <KMainWindow>
#include <KLineEdit>
#include <QLabel>
 
#include <attica/providermanager.h>
#include <attica/provider.h>
 
class MainWindow : public KMainWindow
{
    Q_OBJECT
 
public:
    MainWindow(QWidget *parent=0);
 
public Q_SLOTS:
    // Here we will get notified, when the provider is loaded
    void providersChanged();
 
private:
    // ProviderManager is the class that lets us "create" providers
    Attica::ProviderManager m_manager;
    // A provider that we will ask for data from openDesktop.org
    Attica::Provider m_provider;
};
#endif

mainwindow.cpp

//mainwindow.cpp
#include "mainwindow.h"
 
#include <KDebug>
#include <QVBoxLayout>
 
#include <attica/providermanager.h>
#include "simplepersonrequest.h"
 
MainWindow::MainWindow(QWidget *parent) : KMainWindow(parent)
{
    // connect to get notified, when new Providers are loaded
    connect(&m_manager, SIGNAL(defaultProvidersLoaded()), SLOT(providersChanged()));
    // tell it to get the default Providers
    m_manager.loadDefaultProviders();
}
 
// called when a provider was loaded
void MainWindow::providersChanged()
{
    if (!m_manager.providers().isEmpty()) {
        m_provider = m_manager.providerByUrl(QUrl("https://api.opendesktop.org/v1/"));
        if (!m_provider.isValid()) {
            kDebug() << "Could not find opendesktop.org provider.";
            return;
        }
        // Use a tab widget here, so we can add more in the next tutorial
        QTabWidget* mainWidget = new QTabWidget(this);
        setCentralWidget(mainWidget);
        // Create a widget that will make use of the Provider
        // and supply information about a Person
        SimplePersonRequest* personWidget = new SimplePersonRequest(m_provider, this);
        mainWidget->addTab(personWidget, tr("Person Search"));
    }
}
#include "mainwindow.moc"

Now we have a simple mainwindow with a tab widget. The real contents is still missing though. The first widget we'll add gives some information about a Person.

Note also that in this case the provider file for the OCS server residing at "https://api.opendesktop.org/v1/" is already loaded calling m_manager.loadDefaultProviders();. If you want to run your custom server you should first load your provider file and then select it using m_manager.providerByUrl() method. Here is a small example quoting only the code that changed:

// [...]
    connect(&m_manager, SIGNAL(defaultProvidersLoaded()), SLOT(providersChanged()));
    // load your custom provider file to ProviderManager list
   m_manager.addProviderFile(QUrl("http://example.com/providers.xml"));
}

void MainWindow::providersChanged()
{
    if (!m_manager.providers().isEmpty()) {
        // this will select and return your provider file using the url 
        m_provider = m_manager.providerByUrl(QUrl("https://example.com/v1/"));
// [...]

Person

Now that we have a Provider, we can ask it for information. As a first step, let's find out who I am. Entering any user nick into a KLineEdit will look up that Person. Here is a class that subclasses QWidget and simply contains two labels that show the real name and city for a Person. Since the Data has to be fetched from the server using a REST API, it is asynchronous. When the data arrived, we get notified by a signal.

simplepersonrequest.h

#ifndef SIMPLEPERSONREQUEST_H
#define SIMPLEPERSONREQUEST_H
 
#include <QtGui/QLabel>
#include <KLineEdit>
#include <attica/provider.h>
 
class SimplePersonRequest :public QWidget
{
    Q_OBJECT
public:
    SimplePersonRequest(Attica::Provider provider, QWidget* parent = 0);
 
public Q_SLOTS:
    // When the user entered a different nick name in the line edit and pressed enter.
    void nickChanged(const QString& nick);
    // The information has been loaded.
    void onPersonJobFinished( Attica::BaseJob *job );
 
private:
    KLineEdit* mNickNameLineEdit;
    QLabel* mNameLabel;
    QLabel* mLocationLabel;
    QString mNick;
    Attica::Provider m_provider;
};
#endif // SIMPLEPERSONREQUEST_H

simplepersonrequest.cpp

Now to the actual implementation of our Widget that shows information about a person:

#include "simplepersonrequest.h"
 
#include <KDebug>
#include <QtGui/QBoxLayout>
#include <QtGui/QSpacerItem>
 
#include <attica/person.h>
#include <attica/itemjob.h>
 
SimplePersonRequest::SimplePersonRequest(Attica::Provider provider, QWidget* parent)
    : QWidget(parent)
    , m_provider(provider)
{
    QVBoxLayout* layout = new QVBoxLayout(this);
 
    mNickNameLineEdit = new KLineEdit();
    layout->addWidget(mNickNameLineEdit);
 
    mNameLabel = new QLabel(this);
    mNameLabel->setText("Name");
    layout->addWidget(mNameLabel);
 
    mLocationLabel = new QLabel(this);
    mLocationLabel->setText("Location");
    layout->addWidget(mLocationLabel);
 
    mNick = "fregl";
    mNickNameLineEdit->setText(mNick);
    // watch the LineEdit for changes
    connect(mNickNameLineEdit, SIGNAL(returnPressed(QString)), SLOT(nickChanged(QString)));
    // load the data
    nickChanged(mNick);
}
 
// The user pressed enter, try to get information about the nick name
void SimplePersonRequest::nickChanged(const QString& nick)
{
    mNick = nick;
    // ask the provider for a job that loads the person information:
    Attica::ItemJob<Attica::Person>* job = m_provider.requestPerson(mNick);
    // connect that job
    connect(job, SIGNAL(finished(Attica::BaseJob*)), SLOT(onPersonJobFinished(Attica::BaseJob*)));
    // start the job
    job->start();
}
 
// New information has arrived
void SimplePersonRequest::onPersonJobFinished( Attica::BaseJob *job )
{
    kDebug() << "onJobFinished";
    // Get the information about the person: we need to turn the job into its proper sub class
    Attica::ItemJob<Attica::Person> *personJob = static_cast< Attica::ItemJob<Attica::Person> * >( job );
    // check if the request actually worked
    if( personJob->metadata().error() == Attica::Metadata::NoError ) {
        // use the data to fill the labels
        Attica::Person p(personJob->result());
        mNameLabel->setText(p.firstName() + ' ' + p.lastName());
        mLocationLabel->setText(p.city());
    } else {
        mNameLabel->setText("Could not fetch information.");
    }
}
#include "simplepersonrequest.moc"

Compiling the example

The last thing missing is a small main.cpp and CMakeLists.txt to complete the example and make it compile:

main.cpp

#include <KApplication>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KLocale>
 
#include "mainwindow.h"
 
int main (int argc, char *argv[])
{
    KAboutData aboutData( "opencollaborationexample", 0,
    ki18n("Open Collaboration Services Demo"), "1.0",
    ki18n("Show how to use libattica to access the Open Collaboration Services"),
    KAboutData::License_GPL,
    ki18n("Copyright (c) 2009 Frederik Gladhorn") );
    KCmdLineArgs::init( argc, argv, &aboutData );
 
    KApplication app;
 
    MainWindow* window = new MainWindow();
    window->show();
 
    return app.exec();
}

CMakeLists.txt

project (opencollaborationexample)

find_package(KDE4 REQUIRED)
find_package(LibAttica REQUIRED)

include_directories(${KDE4_INCLUDES}  ${ATTICA_INCLUDE_DIRS}
    ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
 
set(opencollaborationexample_SRCS
    main.cpp
    mainwindow.cpp
    simplepersonrequest.cpp
)

qt4_automoc(opencollaborationexample_SRCS) 
kde4_add_executable(opencollaborationexample ${opencollaborationexample_SRCS})
target_link_libraries(opencollaborationexample  ${LIBATTICA_LIBRARIES}
    ${KDE4_KIO_LIBS}  ${KDE4_KDEUI_LIBS})