Example #1
0
bool TestExec(const wxVector<wxFileName>& programs, long timeout)
{
    size_t i;
    wxVector<MonitorData*> data;

    // run all programs specified as command line parameters
    wxArrayLong procID;
    for (i=0; i<programs.size(); i++)
    {
        MonitorData *dt = new MonitorData(programs[i].GetFullPath());

        long pid = wxExecute(programs[i].GetFullPath(), wxEXEC_ASYNC, &dt->process);
        if (pid == 0)
        {
            wxLogError("could not run the program '%s'", programs[i].GetFullPath());
        }
        else
        {
            wxLogMessage("started program '%s' (pid %d)...",
                         programs[i].GetFullPath(), pid);
            wxASSERT(dt->process.GetPid() == pid);

            data.push_back(dt);
        }
    }

    // sleep some moments
    wxSleep(timeout);

    // check if all processes are still running
    bool allok = true;
    for (i=0; i<data.size(); i++)
    {
        MonitoredProcess& proc = data[i]->process;
        const wxString& prog = data[i]->program;

        if (wxProcess::Exists(proc.GetPid()))
            proc.Kill();
        else
        {
            // this typically never happens, at least when running wx-programs
            // built with debug builds of wx (see MonitoredProcess::OnTerminate;
            // even if an asserts fail the app doesn't automatically close!):

            wxLogMessage("program '%s' (pid %d) is NOT running anymore...",
                         prog, proc.GetPid());
            allok = false;
        }

        if (data[i]->process.Crashed())
        {
            allok = false;
            wxLogMessage("program '%s' (pid %d) crashed...",
                         prog, proc.GetPid());
        }
        else
            wxLogMessage("program '%s' (pid %d) ended with exit code %d...",
                         prog, proc.GetPid(), proc.GetExitCode());
    }

    return allok;
}
Example #2
0
// Uploads a deck to secret library
bool DeckUpload::Upload(wxString &sCrypt, wxString &sLibrary, wxString &sTitle, wxString &sAuthor, wxString &sDesc, wxString &sUserName, wxString &sPassword)
{
    bool result = FALSE;
    wxHTTP httpPost;
    wxString postBuffer = wxT("");
    int timeoutCount = 0;

    httpPost.SetHeader(wxT("Content-type"), wxT("application/x-www-form-urlencoded"));
    httpPost.SetTimeout(10); // 10 seconds of timeout instead of 10 minutes ...

    postBuffer += wxT("sl_deck_submit=1&");
    postBuffer += wxT("sl_user_agent=ardb&");
    postBuffer += wxT("sl_agent_version=2.9.0&");
    postBuffer += wxT("username="******"&");
    postBuffer += wxT("password="******"&");
    postBuffer += wxT("title=") + UriEncode(sTitle) + wxT("&");
    postBuffer += wxT("author=") + UriEncode(sAuthor) + wxT("&");
    postBuffer += wxT("description=") + UriEncode(sDesc) + wxT("&");
    postBuffer += wxT("public=1&");
    postBuffer += wxT("crypt=");
    postBuffer += UriEncode(sCrypt);
    postBuffer += wxT("&");
    postBuffer += wxT("library=");
    postBuffer += UriEncode(sLibrary);

    httpPost.SetPostBuffer(postBuffer);

    while (!httpPost.Connect(wxT("www.secretlibrary.info"))) { // only the server, no pages here yet ...
        wxSleep(5);
        timeoutCount++;

        if (timeoutCount > 4) {

            break;
        }
    }

    wxInputStream *httpStream = httpPost.GetInputStream(wxT("/api.php"));

    if (httpPost.GetError() == wxPROTO_NOERR) {
        wxString res;
        int idx;

        wxStringOutputStream out_stream(&res);
        httpStream->Read(out_stream);

        idx = res.Find(wxT(':'));

        if (idx != wxNOT_FOUND) {
            if (res.BeforeFirst(wxT(':')) == wxT('0')) {
                wxMessageBox(res.Mid(idx+1),wxT("Deck Uploaded"));
            } else {
                wxMessageBox(res.Mid(idx+1),wxT("Secret Library Error"));
            }
        }

        result = TRUE;
    }

    return result;

}
//    Entry Point
void *OCP_DataStreamInput_Thread::Entry()
{
    wxString msg;
    OVERLAPPED osReader = {0};
    OVERLAPPED osWriter = {0};
    
    m_launcher->SetSecThreadActive();               // I am alive
    
    wxSleep(1);         //  allow Bluetooth SPP connections to re-cycle after the parent's test for existence.
                        //  In the MS Bluetooth stack, there is apparently a minimum time required
                        //  between CloseHandle() and CreateFile() on the same port.
                        // FS#1008

    bool not_done;
    HANDLE hSerialComm = (HANDLE)(-1);
    int max_timeout = 5;
    int loop_timeout = 2000;
    int n_reopen_wait = 2000;
    bool nl_found = false;
    bool b_burst_read = false;
    int dcb_read_toc = 2000;
    int dcb_read_tom = MAXDWORD;
    bool b_sleep = false;

       //    Request the com port from the comm manager
    if ((m_gps_fd = OpenComPortPhysical(m_PortName, m_baud)) < 0)
    {
        wxString msg(_T("NMEA input device initial open failed: "));
        msg.Append(m_PortName);
        wxString msg_error;
        msg_error.Printf(_T("...GetLastError():  %d"), GetLastError());
        msg.Append(msg_error);

        ThreadMessage(msg);
        m_gps_fd = 0;
//        goto thread_exit;
    }

    hSerialComm = (HANDLE)m_gps_fd;

    COMMTIMEOUTS timeouts;

    //  Short read timeout for faster response
    timeouts.ReadIntervalTimeout = 1;
    timeouts.ReadTotalTimeoutMultiplier = 0;
    timeouts.ReadTotalTimeoutConstant = 0;
    timeouts.WriteTotalTimeoutMultiplier = 0;
    timeouts.WriteTotalTimeoutConstant = 500; 
    
    
    if(m_gps_fd){
        if (!SetCommTimeouts(hSerialComm, &timeouts)){ // Error setting time-outs.
            CloseComPortPhysical(m_gps_fd);
            m_gps_fd = 0;
        }            
    }

      // Create the reader overlapped event.
    osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    // Create the writer overlapped event.
    osWriter.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    
      
    not_done = true;

#define READ_BUF_SIZE 200
    char szBuf[READ_BUF_SIZE];
    
#define READ_TIMEOUT      50      // milliseconds
    
    DWORD dwRead;
    DWORD dwWritten;
    DWORD dwRes;
    DWORD dwToWrite;

    int n_timeout = 0;
    
    bool fWaitingOnRead = false;
    bool fWaitingOnWrite = false;
    
    
//    The main loop

    while(not_done)
    {
        if(TestDestroy())
            not_done = false;                               // smooth exit

       //    Was port closed due to error condition?
        while(!m_gps_fd)
        {
            if((TestDestroy()) || (m_launcher->m_Thread_run_flag == 0))
                goto thread_exit;                               // smooth exit

            if(n_reopen_wait){
                int nrwd10 = wxMax(1, n_reopen_wait /10);

                while(n_reopen_wait > 0){
                    wxThread::Sleep(nrwd10);                        // stall for a bit
                    
                    if((TestDestroy()) || (m_launcher->m_Thread_run_flag == 0))
                        goto thread_exit;                               // smooth exit
                    
                    n_reopen_wait -= nrwd10;
                }
                        
                n_reopen_wait = 0;
            }


            if ((m_gps_fd = OpenComPortPhysical(m_PortName, m_baud)) > 0)
            {
                hSerialComm = (HANDLE)m_gps_fd;

                wxThread::Sleep(100);                        // stall for a bit
                
                if (!SetCommTimeouts(hSerialComm, &timeouts)){ // Error setting time-outs.
                      int errt = GetLastError();                // so just retry
                      CloseComPortPhysical(m_gps_fd);
                      m_gps_fd = 0;
                      
                }
                
                fWaitingOnWrite = FALSE;
                fWaitingOnRead = FALSE;
                n_timeout = 0;
                
            }
            else
            {
                m_gps_fd = 0;
                
                int nwait = 2000;
                while(nwait > 0){
                    wxThread::Sleep(200);                        // stall for a bit
                    
                    if((TestDestroy()) || (m_launcher->m_Thread_run_flag == 0))
                        goto thread_exit;                               // smooth exit
                        
                    nwait -= 200;
                }
            }
        }

        if( (m_io_select == DS_TYPE_INPUT_OUTPUT) || (m_io_select == DS_TYPE_OUTPUT) ) {
                m_outCritical.Enter();
                bool b_qdata = !out_que.empty();
                    
                bool b_break = false;
                while(!b_break && b_qdata){
                    char msg[MAX_OUT_QUEUE_MESSAGE_LENGTH];
                    
//                    printf("wl %d\n", out_que.size());
                    {
                        
                        if(fWaitingOnWrite){
//                            printf("wow\n");
                            dwRes = WaitForSingleObject(osWriter.hEvent, INFINITE);
                            
                            switch(dwRes)
                            {
                                case WAIT_OBJECT_0:
                                    if (!GetOverlappedResult(hSerialComm, &osWriter, &dwWritten, FALSE)) {
                                        if (GetLastError() == ERROR_OPERATION_ABORTED){
                                            //    UpdateStatus("Write aborted\r\n");
                                        }
                                        else{
                                            b_break = true;
                                        }
                                    }
                                    
                                    if (dwWritten != dwToWrite) {
                                        //ErrorReporter("Error writing data to port (overlapped)");
                                    }
                                    else {
                                        // Delayed write completed
                                        fWaitingOnWrite = false;
//                                        printf("-wow\n");
                                    }
                                    break;
                                    
                                //                
                                // wait timed out
                                //
                                case WAIT_TIMEOUT:
                                    break;
                                    
                                case WAIT_FAILED:
                                default:
                                    break;
                            }
                            
                        }
                        if(!fWaitingOnWrite){          // not waiting on Write, OK to issue another
                        
                        //  Take a copy of message
                            char *qmsg = out_que.front();
                            strncpy( msg, qmsg, MAX_OUT_QUEUE_MESSAGE_LENGTH-1 );
                            out_que.pop();
                            free(qmsg);
 
                            dwToWrite = strlen(msg);
                            //
                            // issue write
                            //
                            n_timeout = 0;
                            
//                            printf("w\n");
                            if (!WriteFile(hSerialComm, msg, dwToWrite, &dwWritten, &osWriter)) {
                                if (GetLastError() == ERROR_IO_PENDING) { 
                                //
                                // write is delayed
                                //
                                    fWaitingOnWrite = true;
//                                    printf("+wow\n");
                                }
                                else{
                                    b_break = true;
                                }
                            }
                            else {
                            //
                            // writefile returned immediately
                            //
                            }

                            b_qdata = !out_que.empty();
                            
                        }
                    }
                    
                } //while b_qdata
                

            
                m_outCritical.Leave();
        }
        
        
        //
        // if no read is outstanding, then issue another one
        //
//        printf("r\n");
        if (!fWaitingOnRead) {
            if (!ReadFile(hSerialComm, szBuf, READ_BUF_SIZE, &dwRead, &osReader)) {
                if (GetLastError() != ERROR_IO_PENDING) {  // read not delayed?
                        CloseComPortPhysical(m_gps_fd);
                        m_gps_fd = 0;
                        fWaitingOnRead = FALSE;
                        n_reopen_wait = 2000;
                }
                else
                    fWaitingOnRead = TRUE;
            }
            else {    // read completed immediately
                n_timeout = 0;
                
                if (dwRead)
                    HandleASuccessfulRead(szBuf, dwRead);
            }
        }
        
        //
        // wait for pending operations to complete
        //
        if ( fWaitingOnRead ) {
            dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT);
            
            switch(dwRes)
            {
                //
                // read completed
                //
                case WAIT_OBJECT_0:
                    if (!GetOverlappedResult(hSerialComm, &osReader, &dwRead, FALSE)) {
                        int err = GetLastError();
                        if (GetLastError() == ERROR_OPERATION_ABORTED){
                        }
                        else{
                                //      Some other error
                            n_reopen_wait = 2000;
                            CloseComPortPhysical(m_gps_fd);
                            m_gps_fd = 0;
                        }
                    }
                    else {      // read completed successfully
                        if (dwRead)
                            HandleASuccessfulRead(szBuf, dwRead);
                    }
                    
                    fWaitingOnRead = FALSE;
                    n_timeout = 0;
                    
                    break;
                    
                case WAIT_TIMEOUT:
                    n_timeout++;
                        
                    break;                       
                    
                default:                // error of some kind with handles
                    fWaitingOnRead = FALSE;
                    break;
            }
        }
        
        if(m_launcher->m_Thread_run_flag <= 0)
            not_done = false;
        
    }           // the big while...



thread_exit:

//          Close the port cleanly
    CloseComPortPhysical(m_gps_fd);

    m_launcher->SetSecThreadInActive();             // I am dead
    m_launcher->m_Thread_run_flag = -1;

    return 0;

}
void
Client::OnWorkerEvent(WorkerEvent& pEvent) {
    switch (pEvent.m_eventType) {
        case WorkerEvent::CONNECTING:
            if (pEvent.isFailed())
            {
                m_statConnecting--;
                m_statFailed++;
            }
        break;
        case WorkerEvent::SENDING:
            if (pEvent.isFailed())
            {
                m_statFailed++;
                m_statSending--;
            }
            else
            {
                m_statConnecting--;
                m_statSending++;
            }
        break;
        case WorkerEvent::RECEIVING:
            if (pEvent.isFailed())
            {
                m_statReceiving--;
                m_statFailed++;
            }
            else
            {
                m_statSending--;
                m_statReceiving++;
            }
        break;
        case WorkerEvent::DISCONNECTING:
            if (pEvent.isFailed())
            {
                m_statDisconnecting--;
                m_statFailed++;
            }
            else
            {
                m_statReceiving--;
                m_statDisconnecting++;
            }
        break;
        case WorkerEvent::DONE:
            m_statDone++;
            m_statDisconnecting--;
        break;
    };

    if (pEvent.isFailed() || pEvent.m_eventType == WorkerEvent::DONE)
    {
        for(TList::compatibility_iterator it = m_threadWorkers.GetFirst(); it ; it = it->GetNext()) {
            if (it->GetData() == pEvent.m_sender) {
                m_threadWorkers.DeleteNode(it);
                break;
            }
        }
        for(EList::compatibility_iterator it2 = m_eventWorkers.GetFirst(); it2 ; it2 = it2->GetNext())
        {
            if (it2->GetData() == pEvent.m_sender) {
                delete it2->GetData();
                m_eventWorkers.DeleteNode(it2);
                break;
            }
        }
        if ((m_threadWorkers.GetCount() == 0) && (m_eventWorkers.GetCount() == 0))
        {
            mTimer.Stop();
            dumpStatistics();
            wxSleep(2);
            ExitMainLoop();
        }
        else
        {
            mTimer.Start(timeout_val,true);
        }
    }
}
void CAccountManagerProcessingPage::OnStateChange( CAccountManagerProcessingPageEvent& WXUNUSED(event) )
{
    CMainDocument* pDoc = wxGetApp().GetDocument();
    CWizardAttach* pWA = ((CWizardAttach*)GetParent());
    wxDateTime dtStartExecutionTime;
    wxDateTime dtCurrentExecutionTime;
    wxTimeSpan tsExecutionTime;
    ACCT_MGR_RPC_REPLY reply;
    wxString strBuffer = wxEmptyString;
    std::string url = "";
    std::string username = "";
    std::string password = "";
    bool bPostNewEvent = true;
    int iReturnValue = 0;
    unsigned int i;
 
    wxASSERT(pDoc);
    wxASSERT(wxDynamicCast(pDoc, CMainDocument));
 
    switch(GetCurrentState()) {
        case ATTACHACCTMGR_INIT:
            pWA->DisableNextButton();
            pWA->DisableBackButton();
            StartProgress(m_pProgressIndicator);
            SetNextState(ATTACHACCTMGR_ATTACHACCTMGR_BEGIN);
            break;
        case ATTACHACCTMGR_ATTACHACCTMGR_BEGIN:
            SetNextState(ATTACHACCTMGR_ATTACHACCTMGR_EXECUTE);
            break;
        case ATTACHACCTMGR_ATTACHACCTMGR_EXECUTE:
            // Attempt to attach to the account manager.

            // Newer versions of the server-side software contain the correct
            //   master url in the get_project_config response.  If it is available
            //   use it instead of what the user typed in.
            if (!pWA->project_config.master_url.empty()) {
                url = pWA->project_config.master_url;
            } else {
                url = (const char*)pWA->m_AccountManagerInfoPage->GetProjectURL().mb_str();
            }

            if (pWA->project_config.uses_username) {
                username = (const char*)pWA->m_AccountInfoPage->GetAccountUsername().mb_str();
            } else {
                username = (const char*)pWA->m_AccountInfoPage->GetAccountEmailAddress().mb_str();
            }
            password = (const char*)pWA->m_AccountInfoPage->GetAccountPassword().mb_str();
            
            // Wait until we are done processing the request.
            dtStartExecutionTime = wxDateTime::Now();
            dtCurrentExecutionTime = wxDateTime::Now();
            tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime;
            iReturnValue = 0;
            reply.error_num = ERR_RETRY;
            while (
                !iReturnValue && 
                ((ERR_IN_PROGRESS == reply.error_num) || (ERR_RETRY == reply.error_num)) &&
                (tsExecutionTime.GetSeconds() <= 60) &&
                !CHECK_CLOSINGINPROGRESS()
            ) {
                if (ERR_RETRY == reply.error_num) {
                    pDoc->rpc.acct_mgr_rpc(
                        url.c_str(),
                        username.c_str(),
                        password.c_str(),
                        pWA->m_bCredentialsCached
                    );
                }
            
                dtCurrentExecutionTime = wxDateTime::Now();
                tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime;
                iReturnValue = pDoc->rpc.acct_mgr_rpc_poll(reply);

                IncrementProgress(m_pProgressIndicator);

                ::wxMilliSleep(500);
                wxEventLoopBase::GetActive()->YieldFor(wxEVT_CATEGORY_USER_INPUT);
            }
    
            if (!iReturnValue && !reply.error_num) {
                SetProjectAttachSucceeded(true);
                pWA->SetAttachedToProjectSuccessfully(true);
            } else {
                SetProjectAttachSucceeded(false);

                if ((ERR_NOT_FOUND == reply.error_num) ||
					(ERR_DB_NOT_FOUND == reply.error_num) ||
                    (ERR_BAD_EMAIL_ADDR == reply.error_num) ||
                    (ERR_BAD_PASSWD == reply.error_num)
                ) {
                    // For any logon error, make sure we do not attempt to use cached credentials
                    //   on any follow-ups.
                    pWA->m_bCredentialsCached = false;
                    SetProjectAccountNotFound(true);
                } else {
                    SetProjectAccountNotFound(false);
                }

                strBuffer = pWA->m_CompletionErrorPage->m_pServerMessagesCtrl->GetLabel();
                if ((HTTP_STATUS_INTERNAL_SERVER_ERROR == reply.error_num)) {
                    strBuffer += 
                        _("An internal server error has occurred.\n");
                } else {
                    for (i=0; i<reply.messages.size(); i++) {
                        strBuffer += wxString(reply.messages[i].c_str(), wxConvUTF8) + wxString(wxT("\n"));
                    }
                }
                pWA->m_CompletionErrorPage->m_pServerMessagesCtrl->SetLabel(strBuffer);
            }
            SetNextState(ATTACHACCTMGR_CLEANUP);
            break;
        case ATTACHACCTMGR_CLEANUP:
            FinishProgress(m_pProgressIndicator);
            SetNextState(ATTACHACCTMGR_END);
            break;
        default:
            // Allow a glimps of what the result was before advancing to the next page.
            wxSleep(1);
            pWA->EnableNextButton();
            pWA->EnableBackButton();
            pWA->SimulateNextButton();
            bPostNewEvent = false;
            break;
    }
 
    Update();
 
    if (bPostNewEvent && !CHECK_CLOSINGINPROGRESS()) {
        CAccountManagerProcessingPageEvent TransitionEvent(wxEVT_ACCOUNTMANAGERPROCESSING_STATECHANGE, this);
        AddPendingEvent(TransitionEvent);
    }
}
Example #6
0
void ModderTask::OnFail(const wxString &errorMsg)
{
	SetStatus(errorMsg);
	wxSleep(3);
	EmitErrorMessage(errorMsg);
}
Example #7
0
void MyFrame::ShowProgress( wxCommandEvent& WXUNUSED(event) )
{
#if wxUSE_STOPWATCH && wxUSE_LONGLONG
    // check the performance
    int countrandomnumbers = 0, count = 0;
    wxTimeSpan tsTest(0,0,0,250);
    wxDateTime DT2, DT1 = wxDateTime::UNow();
    srand(0);
    while(1)
    {
        rand();
        ++countrandomnumbers;
        if ( countrandomnumbers == 1000 )
        {
            srand(0);
            countrandomnumbers = 0;
            ++count;
            DT2 = wxDateTime::UNow();
            wxTimeSpan ts = DT2.Subtract( DT1 );
            if ( ts.IsLongerThan( tsTest ) )
            {
                break;
            }
        }
    }
    const int max = 40 * count;
#else
    static const int max = 10;
#endif // wxUSE_STOPWATCH && wxUSE_LONGLONG

    wxProgressDialog dialog(_T("Progress dialog example"),
                            _T("An informative message"),
                            max,    // range
                            this,   // parent
                            wxPD_CAN_ABORT |
                            wxPD_CAN_SKIP |
                            wxPD_APP_MODAL |
                            // wxPD_AUTO_HIDE | -- try this as well
                            wxPD_ELAPSED_TIME |
                            wxPD_ESTIMATED_TIME |
                            wxPD_REMAINING_TIME |
                            wxPD_SMOOTH);

    bool cont = true;
    bool skip = false;
    // each skip will move progress about quarter forward
    for ( int i = 0; i <= max; i = wxMin(i+(skip?int(max/4):1), max+1), skip = false )
    {
#if wxUSE_STOPWATCH && wxUSE_LONGLONG
        // do (almost) the same operations as we did for the performance test
        srand(0);
        for ( int j = 0; j < 1000; j++ )
        {
            rand();
            if ( j == 999 )
            {
                DT2 = wxDateTime::UNow();
                wxTimeSpan ts = DT2.Subtract( DT1 );
                if ( ts.IsLongerThan( tsTest ) )
                {
                    // nothing to do
                }
            }
        }
#else
        wxSleep(1);
#endif

        wxString msg;

        if ( i == max )
        {
            msg = _T("That's all, folks!");
        }
        else if ( i > max / 2 )
        {
            msg = _T("Only a half left (very long message)!");
        }

#if wxUSE_STOPWATCH && wxUSE_LONGLONG
        if ( (i % (max/100)) == 0 ) // // only 100 updates, this makes it much faster
        {
            cont = dialog.Update(i, msg, &skip);
        }
#else
        cont = dialog.Update(i, msg, &skip);
#endif

        if ( !cont )
        {
            if ( wxMessageBox(_T("Do you really want to cancel?"),
                              _T("Progress dialog question"),  // caption
                              wxYES_NO | wxICON_QUESTION) == wxYES )
                break;

            cont = true;
            dialog.Resume();
        }
    }

    if ( !cont )
    {
        wxLogStatus(wxT("Progress dialog aborted!"));
    }
    else
    {
        wxLogStatus(wxT("Countdown from %d finished"), max);
    }
}
Example #8
0
int main (int argn, char ** argc)
{
	wxSleep (10);
	BOOL success = StartServiceCtrlDispatcher(gimusvc);
	return 0;
}
Example #9
0
void MainFrame::Check(wxCommandEvent& event)
{
	results->SetDefaultStyle(wxTextAttr(*wxBLUE));
	results->AppendText(wxT("\n[INFO] User starts a check procress"));

	wxHTTP get;
	get.SetHeader(wxT("Content-Type"),wxT("text/html; charset=utf8"));
	results->AppendText(wxT("\n[Request] Content-Type: text/html; charset=utf8"));
	get.SetHeader(wxT("User-Agent"),wxT("DivVerifyHTTP/1.0 wxHTTP/2.8 (+http://github.com/AdrianArroyoCalle/divwork)"));
	results->AppendText(wxT("\n[Request] User-Agent: DivVerifyHTTP/1.0 wxHTTP/2.8 (+http://github.com/AdrianArroyoCalle/divwork)"));
	get.SetHeader(wxT("Accept-Charset"),wxT("utf-8"));
	results->AppendText(wxT("\n[Request] Accept-Charset: utf-8"));
	get.SetHeader(wxT("X-Requested-With"),wxT("DivVerifyHTTP"));
	results->AppendText(wxT("\n[Request] X-Requested-With: DivVerifyHTTP"));
	get.SetHeader(wxT("DNT"),wxT("1"));
	results->AppendText(wxT("\n[Request] DNT: 1"));
	get.SetTimeout(10);

	while (!get.Connect(server->GetValue().BeforeFirst('/')))  // only the server, no pages here yet ...
    wxSleep(5);

	results->AppendText(wxT("\n[INFO] Server host: ")+server->GetValue().BeforeFirst('/'));

	if(server->GetValue().AfterFirst('/').Cmp(wxT(""))==0)
	{
		wxInputStream *httpStream = get.GetInputStream(wxT("/"));
		results->AppendText(wxT("\n[INFO] Server page: /"));
	}else{
		wxInputStream *httpStream = get.GetInputStream(server->GetValue().AfterFirst('/'));
		results->AppendText(wxT("\n[INFO] Server page: ")+server->GetValue().AfterFirst('/'));
	}

	results->SetDefaultStyle(wxTextAttr(*wxGREEN));
	results->AppendText(wxString::Format(wxT("\n[Response] HTTP Code: %d"),get.GetResponse()));
	results->AppendText(wxT("\n[Response] X-Powered-By: ")+get.GetHeader(wxT("X-Powered-By")));
	results->AppendText(wxT("\n[Response] Access-Control-Allow-Origin: ")+get.GetHeader(wxT("Access-Control-Allow-Origin")));
	results->AppendText(wxT("\n[Response] Date:")+get.GetHeader(wxT("Date")));
	results->AppendText(wxT("\n[Response] Content-Type: ")+get.GetHeader(wxT("Content-Type")));
	results->AppendText(wxT("\n[Response] Location: ")+get.GetHeader(wxT("Location")));

	switch(get.GetError())
	{
	case wxPROTO_NOERR: {
							results->SetDefaultStyle(wxTextAttr(*wxGREEN));
							results->AppendText(wxT("\n[OK] All almost good"));
						}break;
	case wxPROTO_NETERR: {
							results->SetDefaultStyle(wxTextAttr(*wxRED));
							results->AppendText(wxT("\n[ERROR] Network error"));
						 }break;
	case wxPROTO_PROTERR: {
							results->SetDefaultStyle(wxTextAttr(*wxRED));
							results->AppendText(wxT("\n[ERROR] Negotiation error"));
						 }break;
	case wxPROTO_CONNERR: {
							results->SetDefaultStyle(wxTextAttr(*wxRED));
							results->AppendText(wxT("\n[ERROR] Connection error"));
						 }break;
	case wxPROTO_INVVAL: {
							results->SetDefaultStyle(wxTextAttr(*wxRED));
							results->AppendText(wxT("\n[ERROR] Invalid argument"));
						 }break;
	case wxPROTO_NOFILE: {
							results->SetDefaultStyle(wxTextAttr(*wxRED));
							results->AppendText(wxT("\n[ERROR] Remote file doesn't exist"));
						 }break;
	default:{
				results->SetDefaultStyle(wxTextAttr(*wxRED));
				results->AppendText(wxT("\n[ERROR] Unknow error"));
			}

	}
	/*wxDELETE(httpStream);*/
	get.Close();
}
Example #10
0
bool wxRemoteHtmlHelpController::DoConnection()
{
    wxString cmd, blank;
    int nsleep;

    blank = wxT("  ");

    // ignored under DDE, host name in TCP/IP based classes
    wxString hostName = wxT("localhost");

    // Create a new client
    if( !m_client ) m_client = new rhhcClient(&isconn_1);

    nsleep = 0;

    // suppress the log messages from MakeConnection()
    {
        wxLogNull nolog;

        //first try to connect assuming server is running
        if( !isconn_1 )
            m_connection = (rhhcConnection *)m_client->MakeConnection(hostName, m_service, wxT("HELP") );

        //if not, start server
        if( !isconn_1 ) {

            wxString stylestr;
            stylestr.Printf( wxT("--Style%d"), m_style );

            cmd = m_appname + blank + m_service + blank + m_windowname + blank + m_book + blank + stylestr;

            m_process = new wxProcess(NULL);
            m_pid = wxExecute( cmd, false, m_process );
            // leaks - wxExecute itself (if not deleted) and in wxExecute at
            // wxExecuteData *data = new wxExecuteData;
            if( m_pid <= 0 ) {
                wxLogError( wxT("wxRemoteHtmlHelpController - Failed to start Help server") );
                return false;
            }
        }

        while ( !isconn_1 )
        {
            //try every second for a while, then leave it to user
            wxSleep(1);
            if( nsleep > 4 ) {
                if ( wxMessageBox( wxT("Failed to make connection to Help server.\nRetry?") ,
                                   wxT("wxRemoteHtmlHelpController Error"),
                                   wxICON_ERROR | wxYES_NO | wxCANCEL ) != wxYES )
                {
                    // no server
                    return false;
                }
            }
            nsleep++;

            m_connection = (rhhcConnection *)m_client->MakeConnection(hostName, m_service, wxT("HELP") );
        }
    }

    if (!m_connection->StartAdvise(wxT("Item"))) {
        wxLogError(wxT("wxRemoteHtmlHelpController - StartAdvise failed") );
        return false;
    }

    return true;
}