How to send a reference of this? - c++

I'm doing my first project with c++ following the MVC pattern. I have a controller class, Session, which has all functions to manage the class "ClientTsFrm", a view. What I want to do it's to communicate to the view class all events that happen. To do that, I'm using the observer pattern, in fact this implementation 1
Session.h Session is also a singleton.
#pragma once
#include "User.h"
#include "Config.h"
#include "../data/message.h"
#include <list>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
#include "../lib/eventtype.h"
#include "../lib/Subject.h"
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/frame.h>
#else
#include <wx/wxprec.h>
#endif
#include <wx/richtext/richtextctrl.h>
#include <wx/grid.h>
typedef std::list<UserPTR> UserList;
typedef std::shared_ptr<UserList> UserListPTR;
/*
* Set and get functions
*/
class Session: public Subject<EventTS>{
public:
static Session* Instance();
private:
Session(); // Private so that it can not be called
Session(Session const&){}; // copy constructor is private
Session& operator=(Session const&){}; // assignment operator is private
static Session* m_pInstance;
public:
private:
Session* m_instance;
ConfigPTR m_config;
UserListPTR m_luser;
char* m_translationEngine;
MessageQueuePTR m_pending;
MessageQueuePTR m_queue;
};
Subject.h
//
// Copyright (c) 2013 Juan Palacios juan.palacios.puyana#gmail.com
// Subject to the BSD 2-Clause License
// - see < http://opensource.org/licenses/BSD-2-Clause>
//
#ifndef SUBJECT_H_
#define SUBJECT_H_
#include <functional>
#include <map>
#include <vector>
#include <utility> // for std::forward
template <typename Event>
class Subject
{
public:
Subject()=default;
template <typename Observer>
void registerObserver(const Event& event, Observer&& observer)
{
observers_[event].push_back(std::forward<Observer>(observer));
}
template <typename Observer>
void registerObserver(Event&& event, Observer&& observer)
{
observers_[std::move(event)].push_back(std::forward<Observer>(observer));
}
void notify(const Event& event) const
{
for (const auto& obs : observers_.at(event)) obs();
}
// disallow copying and assigning
Subject(const Subject&)=delete;
Subject& operator=(const Subject&)=delete;
private:
std::map<Event, std::vector<std::function<void()>>> observers_;
};
#endif // SUBJECT_H_
ClientTsFrm.h
#pragma once
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/frame.h>
#else
#include <wx/wxprec.h>
#endif
#include "../Data/config.h"
#include "../lib/ClientTS.h"
#include "../data/Session.h"
#include "../data/Message.h"
#include "FrmMailSending.h"
#include "FrmSettingMail.h"
#include "AudioWizard.h"
#include "NationList.h"
#include "LoginWarnings.h"
#include "../ArchiveLog.h"
#include "FrmSaveChat.h"
#include <wx/sizer.h>
#include <wx/wx.h>
#include <wx/timer.h>
#include <wx/stattext.h>
#include <wx/richtext/richtextctrl.h>
#include <wx/textctrl.h>
#include <wx/button.h>
#include <wx/grid.h>
#include "../GlobalVariables.h"
#include "../translateController/translateController.h"
#include "../translateController/translateVariable.h"
#include <list>
//#include "../lib/Observer.h"
#define MENU_ESCI 1800
#define MENU_OPZIONI 1801
#define MENU_SPEECH 1802
class ClientTsFrm : public wxFrame
{
ClientTsFrm(LoginWarnings *warn, wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("TeamTranslate"),
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxCAPTION | wxSYSTEM_MENU | wxCLOSE_BOX | wxRESIZE_BORDER);
virtual ~ClientTsFrm(){};
ClientTsFrm(const ClientTsFrm& tg) {
std::cout << "\tSimpleCat(SimpleCat&) called\n";
}
void updatePanelMsg();
private:
unsigned int curRow; //Initialize Row index
unsigned int curCol; //Initialize Column index
Session* session;
ConfigPTR config;
NationList *nations;
int REFRESHTIMER = 0;
uint64 _sclogID;
wxTimer *WxTimer2;
wxTimer *WxTimer1;
wxButton *btnspeech;
wxRichTextCtrl *txtclient;
wxTextCtrl *txtlingua;
wxStaticText *lbllingua;
wxStaticText *lblnick;
wxTextCtrl *txtnick;
wxRichTextCtrl *txtchat;
wxButton *btnsend;
wxTextCtrl *txtmsg;
wxGrid *gridchat;
wxGrid *gridclient;
wxBoxSizer *sizer;
wxGridSizer *gridsizer;
wxMenuBar *WxMenuBar1;
wxMenu *ID_MNU_FILE_1001_Mnu_Obj;
wxMenu *ID_MNU_OPZIONI_1004_Mnu_Obj;
wxBitmapButton *WxBitmapButton1;
ClientTS clientts;
};
ClientTS.cpp. This is how I register the object
...
session->registerObserver(EventTS::MSG_RCV, std::bind(notifyMSG, *this));
...
void notifyMSG(ClientTsFrm *fn)
{
fn->updatePanelMsg();
}
Basically, I'm registering ClientTSFrm object. It's stored in session class and when an event happens, session calls the "notify" function from the subject class. This function calls the function of ClientTSFrm (the observer) which is send also the object. At the end, this function calls a function of ClientTSFrm class in order to update the content.
If I compile, it shows this error:
Error 28 error C2664: 'void (ClientTsFrm *)' : cannot convert argument
1 from 'ClientTsFrm' to 'ClientTsFrm *' C:\Program Files
(x86)\Microsoft Visual Studio 12.0\VC\include\functional 1149 1
https://github.com/juanchopanza/cppblog/blob/master/Patterns/Observer/

Related

QThreadPoolServer is not responding

I wrote a simple threadpool server with qt. When i try to connect to server on win 32/64 all works good. But when I use linux centos 7 server is not responding. I use 127.0.0.1:8080 for server address. Also server uses database mysql. When I try to connect via telnet it connects but nothing happens. I checked for open ports with netstat. Maybe I missed something because of this the server is not working?
Here is my code for server. In fact, there is also an http request handler, but it does not reach it, I tried to output a string in the constructor - it is not called.
QthreadPoolServer.cpp
#include "QThreadPoolServer.h"
#include "QSocketRunnable.h"
#include "ConfigReader.h"
#include <memory>
QThreadPoolServer::QThreadPoolServer()
{
ConfigReader reader(config_file_path);
QHostAddress server_IP(reader.getServerAddress());
int port = reader.getServerPort();
listen(QHostAddress::localhost, 8080);
std:: cout << serverError() << errorString().toStdString();
m_threadPool = std::make_shared<QThreadPool>(this);
}
void QThreadPoolServer::incomingConnection(int handle)
{
std::shared_ptr<QSocketRunnable> runnable = std::make_shared<QSocketRunnable>(handle);
runnable->setAutoDelete(false);
m_threadPool->start(runnable.get());
}
QThreadPoolServer::~QThreadPoolServer()
{
m_threadPool->~QThreadPool();
}
QThreadPoolServer.h
#ifndef QTHREADPOOLSERVER_H
#define QTHREADPOOLSERVER_H
#include <QTcpServer>
#include <QThreadPool>
#include <memory>
class QThreadPoolServer : public QTcpServer
{
public:
explicit QThreadPoolServer();
void incomingConnection(int handle);
~QThreadPoolServer();
private:
std::shared_ptr<QThreadPool> m_threadPool;
};
#endif // QTHREADPOOLSERVER_H
QSocketRunnable.cpp
#include "QSocketRunnable.h"
#include <QString>
#include <memory>
#include <iostream>
QSocketRunnable::QSocketRunnable(int handle) : m_descriptor(handle) { }
void QSocketRunnable::run()
{
QTcpSocket* socket = new QTcpSocket();
socket->setSocketDescriptor(m_descriptor);
socket->waitForReadyRead();
QString request_data = QString(socket->readAll());
HttpRequestHandler handler(request_data);
handler.makeResponse();
QString http_response_result = handler.getHttpResponse();
std::cout << http_response_result.toStdString() << "\n";
socket->write(http_response_result.toUtf8());
socket->waitForBytesWritten(90000);
socket->disconnectFromHost();
socket->close();
socket->deleteLater();
}
QSocketRunnable.h
#ifndef QSOCKETRUNNABLE_H
#define QSOCKETRUNNABLE_H
#include <QRunnable>
#include <QTcpSocket>
#include <QtDebug>
#include <QString>
//#include "IDHelper.h"
//#include "JsonFormatter.h"
//#include "HttpRequestHandler.h"
class QSocketRunnable : public QRunnable
{
public:
QSocketRunnable(int handle);
void run() override;
private:
int m_descriptor;
};
#endif // QSOCKETRUNNABLE_H
main.cpp
#include <QCoreApplication>
#include "QThreadPoolServer.h"
#include "signal.h"
#include <sstream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThreadPoolServer server;
return a.exec();
}
Also std:: cout << serverError() << errorString().toStdString(); returns "-1" that means QAbstractSocket::UnknownSocketError -1 An unidentified error occurred.
As #chehrlic correctly noted: I had an incorrectly overloaded function, so here is the ritht version of QThreadPoolServer.h
QThreadPoolServer.h
#ifndef QTHREADPOOLSERVER_H
#define QTHREADPOOLSERVER_H
#include <QTcpServer>
#include <QThreadPool>
#include <memory>
class QThreadPoolServer : public QTcpServer
{
public:
explicit QThreadPoolServer();
protected:
void incomingConnection(qintptr handle) override;
~QThreadPoolServer();
private:
std::shared_ptr<QThreadPool> m_threadPool;
};
#endif // QTHREADPOOLSERVER_H
My my implementation did not work correctly with a smart pointer to a runnable object:
QThreadPoolServer.cpp
void QThreadPoolServer::incomingConnection(qintptr handle)
{
QSocketRunnable* runnable = new QSocketRunnable(handle)
runnable->setAutoDelete(true);
m_threadPool->start(runnable);
}

C++ Compile error:'HelpModel' was not declared in this scope - using an optional

I'm getting the following error when compiling, using GCC 11.2.0:
/src/SearchController.h:12:23: error: ‘HelpModel’ was not declared in this scope
12 | std::optional<HelpModel> searchModel;
| ^~~~~~~~~
/src/SearchController.h:12:32: error: template argument 1 is invalid
12 | std::optional<HelpModel> searchModel;
| ^
I'm including the HelpModel class in the header, but this is pretty much my first C++ program so my understanding of this is pretty thin at the min.
Here's the SearchControlle.h file
#ifndef ARCH_HELP_SEARCH_CONTROLLER
#define ARCH_HELP_SEARCH_CONTROLLER
#include <string>
#include <optional>
#include "HelpModel.h"
class SearchController
{
public:
std::optional<HelpModel> searchModel;
void searchedFor(std::string searchTerm);
};
#endif
And here's the HelpModel.h file:
#ifndef ARCH_HELP_HELP_MODEL
#define ARCH_HELP_HELP_MODEL
#include <vector>
#include "Topic.h"
#include "TerminalView.h"
class HelpModel
{
public:
HelpModel(TerminalView view);
private:
TerminalView view;
std::vector<Topic> topics;
void getTopics();
void pushToView();
};
#endif
Here's TerminalView.h
#ifndef ARCH_HELP_TERMINAL_VIEW
#define ARCH_HELP_TERMINAL_VIEW
#include <vector>
#include <string>
#include "SearchController.h"
#include "Topic.h"
class TerminalView
{
public:
void makeHeader();
void update(std::vector<Topic> modelData);
private:
std::string searchTerm;
std::vector<Topic> helpData;
SearchController controller;
void makeSearchInput();
void printToTerminal();
void printAnswers(std::vector<std::string> answers);
};
#endif
What I would like to be able to do is then assign an instance of HelpModel to the SearchController like so - say in main.cpp:
HelpModel model(terminal);
SearchController controller;
controller.searcModel = model;
Any advice greatly appreciated

Template class CArray compile under gcc, Error: the class which used as a parameter of a function undeclared

#ifndef _ALLOCATOR_H
#define _ALLOCATOR_H
#include "ace/OS_NS_stdio.h"
#include "ace/OS_NS_string.h"
#include "ace/MMAP_Memory_Pool.h"
#include "ace/Malloc_T.h"
#include "ace/Null_Mutex.h"
#include "ace/PI_Malloc.h"
#include "ace/OS_NS_unistd.h"
#include "ace/Thread_Mutex.h"
#include "ace/Process_Mutex.h"
#include <string>
using namespace std;
class CAllocator
{
public:
CAllocator();
~CAllocator(void);
public:
bool Create(char* strPoolName);
void Destroy();
public:
char* NewMem(char* strBlockName,int nBlockSize);
char* FindMem(char* strBlockName);
bool FreeMem(char* strBlockName);
private:
typedef ACE_Malloc_T <ACE_MMAP_MEMORY_POOL,
ACE_Process_Mutex,
ACE_PI_Control_Block>
ALLOCATOR;
ALLOCATOR* m_pAllocator;
};
#endif //_ALLOCATOR_H
#ifndef _ARRAY_H
#define _ARRAY_H
#include "allocator.h"
template<typename T>
class CArray
{
public:
bool CreateArray(CAllocator* pAllocator,char* strArrayName,int nArraySize);
bool OpenArray(CAllocator* pAllocator,char* strArrayName);
public:
CArray()
{
m_pArrayData = NULL;
}
~CArray()
{
m_pArrayData = NULL;
}
public:
T* GetObject(int nIndex);
int GetArraySize();
private:
T* m_pArrayData;
};
#include "array.cpp"
#endif //_ARRAY_H
In the function CreateArray of the template class CArray,
the gcc compiler says CAllocator has not been declared.
but all the code worked under vs2010
please help,thanks gurus
Please stop naming like _ALLOCATOR_H. Name start with __ or _ followed by a capital letter is reserved for using by compiler and standard.
– Danh
change #ifndef _ALLOCATOR_H #define _ALLOCATOR_H to #ifndef ALLOCATOR_H #define ALLOCATOR_H Everything is ok! Thank u all – Jack

Usage of vector + inheritance

What I'd like to do, is add an object to my obiektGeometryczny vector, which would be a Manipulator or kwadrat type.
I want "przeszkoda" to be an obstacle of Manipulator or kwadrat (square in polish) type.
I've tried to use:
obiektGeometryczny.push_back(new Manipulator());
but it returns:
src/scena.cpp:71:36: error: expected type-specifier before ‘*’ token
obiektGeometryczny.push_back(new *Manipulator);
Below is the code:
scena.hh
#ifndef SCENA_HH
#define SCENA_HH
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <unistd.h>
#include <vector>
#include "manipulator.hh"
#include "kwadrat.hh"
#include "przeszkoda.h"
class scena{
vector<przeszkoda*> obiektGeometryczny;
public:
scena(int argc, char *argv[]);
};
#endif
przeszkoda.hh
#ifndef PRZESZKODA_HH
#define PRZESZKODA_HH
class przeszkoda{
virtual void czyPrzeciecie() {;};
};
#endif
manipulator.hh
#ifndef MANIPULATOR_HH
#define MANIPULATOR_HH
#include "przeszkoda.hh"
class Manipulator : public przeszkoda
{
void czyPrzeciecie();
};
#endif
kwadrat.hh
#ifndef KWADRAT_HH
#define KWADRAT_HH
#include "przeszkoda.hh"
class kwadrat : public przeszkoda
{
void czyPrzeciecie();
};
#endif
It is not minimal example - there is something more you didn't show us. Code you posted is ok - try to simplify your case, because something like this works correctly:
#include <vector>
using namespace std;
class A {
int x;
};
int main(void) {
vector<A*> v;
v.push_back(new A());
return 0;
}

Error with default constructor [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I post all the files of my project, It seems to be done correct, but this error is incomprensible for me...
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include "IfacomAmqSender.h"
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow,public MessageListener
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void onMessage(const Message*);
void connetionSender();
IfacomAmqSender m_IfacomMessageBroker;
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "IfacomAmqSender.h"
#include "IfacomAmqReceiver.h"
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include <qstring.h>
#include <QTextStream>
#include <QMessageBox>
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::connetionSender()
{
activemq::library::ActiveMQCPP::initializeLibrary();
std::string brokerURI = "failover://(tcp://localhost:61613?wireFormat=stomp)"; // localhost;
// brokerURI = "failover://(tcp://localhost:61616)"; // localhost
// Queue name
std::string destName = "IFACOM-CMS";
// Queue or Topic
bool useTopics = false; // true=Topic, false=Queue
// SESSION_TRANSACTED or AUTO_ACKNOWLEDGE
bool sessionTransacted = false; // if true, commit all messages
// ***** Initialisation **************************************************************
IfacomAmqSender m_IfacomMessageBroker(brokerURI, useTopics, sessionTransacted, destName);
m_IfacomMessageBroker.initConnection();
IfacomAmqReceiver IfacomAmqReceiverBroker(brokerURI,10, useTopics, sessionTransacted, destName,2000);
IfacomAmqReceiverBroker.initConnection();
IfacomAmqReceiverBroker.getConsumer()->setMessageListener(this);
}
void MainWindow::on_pushButton_clicked()
{
//****** Send message ******************************************************
//IfacomAmqSender IfacomAmqReceiverBroker;
std::string text = "My IFaCOM message";
// Customized message
try{
std::auto_ptr<TextMessage> message(m_IfacomMessageBroker.getSession()->createTextMessage(text));
message->setCMSTimestamp(System::currentTimeMillis());
message->setStringProperty("MyProperty", "test");
m_IfacomMessageBroker.sendMessage(message);
} catch (CMSException& e) {
e.printStackTrace();
}
// Simple text message
m_IfacomMessageBroker.sendMessage(text);
long long startTime = System::currentTimeMillis();
long long endTime = System::currentTimeMillis();
double totalTime = (double)(endTime - startTime) / 1000.0;
// Close the connection
m_IfacomMessageBroker.close();
//ui->label->setText(QString::fromStdString(text));
// To Do at the end
//activemq::library::ActiveMQCPP::shutdownLibrary();
}
//***************** Receive Message *****************************************************
void MainWindow::onMessage(const Message* message) {
try {
const TextMessage* textMessage = dynamic_cast<const TextMessage*> (message);
string text = "";
if (textMessage != NULL) {
text = textMessage->getText();
} else {
text = "NOT A TEXTMESSAGE!";
}
//printf("Message received: %s\n", text.c_str());
//WM get param.
std::string msgId = message->getCMSMessageID();
int prio = message->getCMSPriority();
long long timestamp = message->getCMSTimestamp();
ui->label->setText(QString::fromStdString(text));
} catch (CMSException& e) {
e.printStackTrace();
}
// Commit all messages.
/*if (this->m_sessionTransacted) {
m_session->commit();
}
// No matter what, tag the count down latch until done.
m_doneLatch.countDown();*/
}
IfacomAmqReceiver.h
#ifndef _IfacomAmqReceiver_h
#define _IfacomAmqReceiver_h
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
class IfacomAmqReceiver : public ExceptionListener, public MessageListener{
private:
CountDownLatch m_latch;
CountDownLatch m_doneLatch;
Connection* m_connection;
Session* m_session;
Destination* m_destination;
MessageConsumer* m_consumer;
MessageProducer* m_producer;
std::auto_ptr<TextMessage> m_message;
long m_waitMillis;
bool m_useTopic;
bool m_sessionTransacted;
std::string m_brokerURI;
std::string m_destName;
DeliveryMode m_message_delivery_mode;
int m_message_priority;
//IfacomAmqReceiver(const IfacomAmqReceiver&);
//IfacomAmqReceiver& operator=(const IfacomAmqReceiver&);
public:
IfacomAmqReceiver(const std::string&, int, bool, bool, const std::string&, int);
virtual ~IfacomAmqReceiver();
void close();
void waitUntilReady() ;
void cleanup();
// MM
void createConnection();
void createSession();
void createDestination();
void createConsumer();
void initConnection();
void onMessage(const Message*);
MessageConsumer* getConsumer();
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
void onException(const CMSException&);
};
#endif
IfacomAmqReceiver.cpp
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include "IfacomAmqReceiver.h"
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
using namespace std;
IfacomAmqReceiver::IfacomAmqReceiver(const std::string& brokerURI, int numMessages, bool useTopic = false, bool sessionTransacted = false, const std::string& destName = "IFACOM-CMS", int waitMillis = 1000) :
m_latch(1),
m_doneLatch(numMessages),
m_connection(NULL),
m_session(NULL),
m_destination(NULL),
m_consumer(NULL),
m_waitMillis(waitMillis),
m_useTopic(useTopic),
m_sessionTransacted(sessionTransacted),
m_destName(destName),
m_brokerURI(brokerURI) {
}
IfacomAmqReceiver::~IfacomAmqReceiver() {
cleanup();
}
void IfacomAmqReceiver::close() {
this->cleanup();
}
void IfacomAmqReceiver::waitUntilReady() {
m_latch.await();
}
//------ Init connexion ---------------
void IfacomAmqReceiver::createConnection()
{
// Create a ConnectionFactory
auto_ptr<ConnectionFactory> connectionFactory(ConnectionFactory::createCMSConnectionFactory(m_brokerURI));
// Create a Connection
m_connection = connectionFactory->createConnection();
m_connection->start();
m_connection->setExceptionListener(this);
}
void IfacomAmqReceiver::createSession()
{
// Create a Session
if (this->m_sessionTransacted == true) {
m_session = m_connection->createSession(Session::SESSION_TRANSACTED);
} else {
m_session = m_connection->createSession(Session::AUTO_ACKNOWLEDGE);
}
}
void IfacomAmqReceiver::createDestination()
{
// Create the destination (Topic or Queue)
if (m_useTopic) {
m_destination = m_session->createTopic(m_destName);
} else {
m_destination = m_session->createQueue(m_destName);
}
}
void IfacomAmqReceiver::createConsumer()
{
m_consumer = m_session->createConsumer(m_destination);
//m_consumer->setMessageListener(this);
}
void IfacomAmqReceiver::initConnection() {
try {
createConnection();
// Create the session
createSession();
// Create the destination (Topic or Queue)
createDestination();
// Create a MessageConsumer from the Session to the Topic or Queue
createConsumer();
// Indicate we are ready for messages.
m_latch.countDown();
// Wait while asynchronous messages come in.
m_doneLatch.await(m_waitMillis);
} catch (CMSException& e) {
// Indicate we are ready for messages.
//latch.countDown();
e.printStackTrace();
}
}
//------ Get the message ---------------
// Called from the consumer since this class is a registered MessageListener.
void IfacomAmqReceiver::onMessage(const Message* message) {}
//--------------------------------------------------
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
void IfacomAmqReceiver::onException(const CMSException& ex AMQCPP_UNUSED) {
printf("CMS Exception occurred. Shutting down client.\n");
ex.printStackTrace();
exit(1);
}
void IfacomAmqReceiver::cleanup() {
if (m_connection != NULL) {
try {
m_connection->close();
} catch (cms::CMSException& ex) {
ex.printStackTrace();
}
}
// Destroy resources.
try {
delete m_destination;
m_destination = NULL;
delete m_consumer;
m_consumer = NULL;
delete m_session;
m_session = NULL;
delete m_connection;
m_connection = NULL;
} catch (CMSException& e) {
e.printStackTrace();
}
}
MessageConsumer* IfacomAmqReceiver::getConsumer()
{
return m_consumer;
}
IfacomAmqSender.h
#ifndef _IfacomAmqSender_h
#define _IfacomAmqSender_h
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
class IfacomAmqSender : public ExceptionListener{
private:
CountDownLatch m_latch;
CountDownLatch m_doneLatch;
Connection* m_connection;
Session* m_session;
Destination* m_destination;
MessageConsumer* m_consumer;
MessageProducer* m_producer;
std::auto_ptr<TextMessage> m_message;
long m_waitMillis;
bool m_useTopic;
bool m_sessionTransacted;
std::string m_brokerURI;
std::string m_destName;
DeliveryMode m_message_delivery_mode;
int m_message_priority;
IfacomAmqSender(const IfacomAmqSender&);
IfacomAmqSender& operator=(const IfacomAmqSender&);
public:
IfacomAmqSender(const std::string&, int, bool, bool, const std::string&, int);
IfacomAmqSender(const std::string&, bool, bool, const std::string&);
virtual ~IfacomAmqSender();
void close();
void waitUntilReady();
void cleanup();
// KH
void createConnection();
void createSession();
void createDestination();
void createProducer();
void initConnection();
virtual void sendMessage(std::string);
// Send a ActiveMQ Message
virtual void sendMessage(std::auto_ptr<TextMessage>);
//--------------------------------------------------
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
virtual void onException(const CMSException&) ;
// Message Priority (0:Lowest - 9:Highest)
void setPriority(int);
int getPriority();
// Message Delivery Mode
void setDeliveryMode(DeliveryMode);
DeliveryMode getDeliveryMode();
Session* getSession();
};
#endif
IfacomAmqSender.cpp
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include "IfacomAmqSender.h"
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
using namespace std;
IfacomAmqSender::IfacomAmqSender(const std::string& brokerURI, int numMessages, bool useTopic = false, bool sessionTransacted = false, const std::string& destName = "IFACOM-CMS", int waitMillis = 1000) :
m_latch(1),
m_doneLatch(numMessages),
m_connection(NULL),
m_session(NULL),
m_destination(NULL),
m_consumer(NULL),
m_waitMillis(waitMillis),
m_useTopic(useTopic),
m_sessionTransacted(sessionTransacted),
m_destName(destName),
m_brokerURI(brokerURI) {
}
IfacomAmqSender::IfacomAmqSender(const std::string& brokerURI, bool useTopic = false, bool sessionTransacted = false, const std::string& destName = "IFACOM-CMS") :
m_latch(1),
m_doneLatch(1),
m_connection(NULL),
m_session(NULL),
m_destination(NULL),
m_consumer(NULL),
m_waitMillis(1000),
m_useTopic(useTopic),
m_sessionTransacted(sessionTransacted),
m_destName(destName),
m_brokerURI(brokerURI) {
}
IfacomAmqSender::~IfacomAmqSender() {
cleanup();
}
void IfacomAmqSender::close() {
this->cleanup();
}
void IfacomAmqSender::waitUntilReady() {
m_latch.await();
}
//------ Init connexion ---------------
void IfacomAmqSender::createConnection()
{
// Create a ConnectionFactory
auto_ptr<ConnectionFactory> connectionFactory(ConnectionFactory::createCMSConnectionFactory(m_brokerURI));
// Create a Connection
m_connection = connectionFactory->createConnection();
m_connection->start();
m_connection->setExceptionListener(this);
}
void IfacomAmqSender::createSession()
{
// Create a Session
if (this->m_sessionTransacted == true) {
m_session = m_connection->createSession(Session::SESSION_TRANSACTED);
} else {
m_session = m_connection->createSession(Session::AUTO_ACKNOWLEDGE);
}
}
void IfacomAmqSender::createDestination()
{
// Create the destination (Topic or Queue)
if (m_useTopic) {
m_destination = m_session->createTopic(m_destName);
} else {
m_destination = m_session->createQueue(m_destName);
}
}
void IfacomAmqSender::createProducer()
{
m_producer = m_session->createProducer(m_destination);
m_producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);
}
void IfacomAmqSender::initConnection() {
try {
createConnection();
// Create the session
createSession();
// Create the destination (Topic or Queue)
createDestination();
// Create a MessageProducer from the Session to the Topic or Queue
createProducer();
m_producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);
// Indicate we are ready for messages.
m_latch.countDown();
// Wait while asynchronous messages come in.
m_doneLatch.await(m_waitMillis);
} catch (CMSException& e) {
// Indicate we are ready for messages.
//latch.countDown();
e.printStackTrace();
}
}
void IfacomAmqSender::sendMessage(string text) {
try {
std::auto_ptr<TextMessage> message(m_session->createTextMessage(text));
// to set a property
////message->setIntProperty("Integer", ix);
m_producer->send(message.get());
message->setCMSTimestamp(System::currentTimeMillis());
} catch (CMSException& e) {
e.printStackTrace();
}
}
// Send a ActiveMQ Message
void IfacomAmqSender::sendMessage(std::auto_ptr<TextMessage> amq_message) {
try {
amq_message->setCMSTimestamp(System::currentTimeMillis());
m_producer->send(amq_message.get());
} catch (CMSException& e) {
e.printStackTrace();
}
}
//--------------------------------------------------
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
void IfacomAmqSender::onException(const CMSException& ex AMQCPP_UNUSED) {
printf("CMS Exception occurred. Shutting down client.\n");
ex.printStackTrace();
exit(1);
}
// Message Priority (0:Lowest - 9:Highest)
void IfacomAmqSender::setPriority(int priority){m_message_priority = priority;}
int IfacomAmqSender::getPriority(){return m_message_priority;}
// Message Delivery Mode
void IfacomAmqSender::setDeliveryMode(DeliveryMode delivery_mode){m_message_delivery_mode = delivery_mode;}
DeliveryMode IfacomAmqSender::getDeliveryMode(){return m_message_delivery_mode;}
Session* IfacomAmqSender::getSession()
{
return m_session;
}
void IfacomAmqSender::cleanup() {
if (m_connection != NULL) {
try {
m_connection->close();
} catch (cms::CMSException& ex) {
ex.printStackTrace();
}
}
// Destroy resources.
try {
delete m_destination;
m_destination = NULL;
delete m_consumer;
m_consumer = NULL;
delete m_session;
m_session = NULL;
delete m_connection;
m_connection = NULL;
} catch (CMSException& e) {
e.printStackTrace();
}
}
main.cpp
#include "ifacomamqsender.h"
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
and the error is:
Error 29 error C2512: 'IfacomAmqSender' : no appropriate default constructor available 42 1 GUI-CMS
In MainWindow you have a member variable called m_IfacomMessageBroker which is a IfacomAmqSender. This class doesn't have a default constructor, so you must call one of its constructors in the initialization list for MainWindow.
You're not doing this, so the compiler assumes you want to call the default construtor, and it notices that there isn't one, so you get the error. The reason there isn't a default constructor if because you've created your own constructors, so the compiler generated default doesn't exist. Therefore if you want a default constructor you need to manually create it.
I don't see a default constructor in the definition of the IfacomAmqSender object, but you have an instance of it in your MainWindow.
You have this line.
IfacomAmqSender m_IfacomMessageBroker;
This is trying to call a no arg constructor, and you don't have one.
You have:
IfacomAmqSender(const std::string&, int, bool, bool, const std::string&, int);
IfacomAmqSender(const std::string&, bool, bool, const std::string&);
... and need:
IfacomAmqSender();
... or you need to assign default values.
If I know right and I do, the default constructor is not available if the programmer is defining a constructor. You have done it, so there is no default constructor, only the ones that you have declared.
No default constructor is available for the specified class, structure, or union. The compiler supplies a default constructor if user-defined constructors are not provided.
If you provide a constructor that takes a non-void parameter, and you want to allow your class to be created with no parameters, you must also provide a default constructor. The default constructor can be a constructor with default values for all parameters.
For More Information refer :
http://msdn.microsoft.com/en-us/library/9zkz8dx6.aspx