static int process_response(u1db_sync_target *st, void *context, u1db_doc_gen_callback cb, char *response, int *target_gen, char **target_trans_id) { int status = U1DB_OK; int i, doc_count; json_object *json = NULL, *obj = NULL, *attr = NULL; const char *doc_id, *content, *rev; const char *tmp = NULL; int gen; const char *trans_id = NULL; u1db_document *doc; json = json_tokener_parse(response); if (json == NULL || !json_object_is_type(json, json_type_array)) { status = U1DB_BROKEN_SYNC_STREAM; goto finish; } doc_count = json_object_array_length(json); if (doc_count < 1) { // the first response is the new_generation info, so it must exist status = U1DB_BROKEN_SYNC_STREAM; goto finish; } obj = json_object_array_get_idx(json, 0); attr = json_object_object_get(obj, "new_generation"); if (attr == NULL) { status = U1DB_BROKEN_SYNC_STREAM; goto finish; } *target_gen = json_object_get_int(attr); attr = json_object_object_get(obj, "new_transaction_id"); if (attr == NULL) { status = U1DB_BROKEN_SYNC_STREAM; goto finish; } tmp = json_object_get_string(attr); if (tmp == NULL) { status = U1DB_BROKEN_SYNC_STREAM; goto finish; } *target_trans_id = strdup(tmp); if (*target_trans_id == NULL) { status = U1DB_NOMEM; goto finish; } for (i = 1; i < doc_count; ++i) { obj = json_object_array_get_idx(json, i); attr = json_object_object_get(obj, "id"); doc_id = json_object_get_string(attr); attr = json_object_object_get(obj, "rev"); rev = json_object_get_string(attr); attr = json_object_object_get(obj, "content"); content = json_object_get_string(attr); attr = json_object_object_get(obj, "gen"); gen = json_object_get_int(attr); attr = json_object_object_get(obj, "trans_id"); trans_id = json_object_get_string(attr); status = u1db__allocate_document(doc_id, rev, content, 0, &doc); if (status != U1DB_OK) goto finish; if (doc == NULL) { status = U1DB_NOMEM; goto finish; } status = cb(context, doc, gen, trans_id); if (status != U1DB_OK) { goto finish; } } finish: if (json != NULL) { json_object_put(json); } return status; }
void am_parseactions(json_object *config) { int i, j; json_object *actions, *subactions, *a; char *type, *v; subaction_t *s; pthread_mutex_lock(&m); for(i = 0; i < actionc; i++) { for(j = 0; j < actionlist[i].subactionc; j++) if(actionlist[i].subactionlist[j].param) free(actionlist[i].subactionlist[j].param); if(actionlist[i].subactionlist) free(actionlist[i].subactionlist); } if(actionlist) free(actionlist); actions = json_object_object_get(config, SO"actions"); actionc = json_object_array_length(actions); actionlist = malloc(actionc * sizeof(action_t)); for(i = 0; i < actionc; i++) { subactions = json_object_object_get(json_object_array_get_idx(actions, i), SO"subactions"); actionlist[i].subactionc = json_object_array_length(subactions); actionlist[i].subactionlist = malloc(actionlist[i].subactionc * sizeof(subaction_t)); actionlist[i].sched = 0; actionlist[i].queue = QUEUE_FAST; for(j = 0; j < actionlist[i].subactionc; j++) { a = json_object_array_get_idx(subactions, j); s = &actionlist[i].subactionlist[j]; s->type = SUBACTION_NONE; if(get_string(a, SO"action", &type)) continue; if(!strcmp(type, SO"uninstall")) { s->param = NULL; s->type = SUBACTION_UNINSTALL; actionlist[i].queue = QUEUE_SLOW; } else if(!strcmp(type, SO"execute")) { if(!(s->param = malloc(sizeof(subaction_execute_t)))) continue; if(get_string(a, SO"command", &v)) continue; snprintf(((subaction_execute_t *)s->param)->command, sizeof(((subaction_execute_t *)s->param)->command), "%s", v); s->type = SUBACTION_EXECUTE; actionlist[i].queue = QUEUE_SLOW; } else if(!strcmp(type, SO"log")) { if(!(s->param = malloc(sizeof(subaction_log_t)))) continue; if(get_string(a, SO"text", &v)) continue; snprintf(((subaction_log_t *)s->param)->text, sizeof(((subaction_log_t *)s->param)->text), "%s", v); s->type = SUBACTION_LOG; } else if(!strcmp(type, SO"synchronize")) { if(!(s->param = malloc(sizeof(subaction_synchronize_t)))) continue; if(get_string(a, SO"host", &v)) continue; snprintf(((subaction_synchronize_t *)s->param)->host, sizeof(((subaction_synchronize_t *)s->param)->host), "%s", v); if(get_int(a, SO"bandwidth", &((subaction_synchronize_t *)s->param)->bandwidth)) continue; if(get_int(a, SO"mindelay", &((subaction_synchronize_t *)s->param)->mindelay)) continue; if(get_int(a, SO"maxdelay", &((subaction_synchronize_t *)s->param)->maxdelay)) continue; if(get_boolean(a, SO"stop", &((subaction_synchronize_t *)s->param)->stop)) continue; s->type = SUBACTION_SYNCHRONIZE; actionlist[i].queue = QUEUE_SLOW; } else if(!strcmp(type, SO"destroy")) { if(!(s->param = malloc(sizeof(subaction_destroy_t)))) continue; if(get_boolean(a, SO"permanent", &((subaction_destroy_t *)s->param)->permanent)) continue; s->type = SUBACTION_DESTROY; } else if(!strcmp(type, SO"event")) { if(!(s->param = malloc(sizeof(subaction_event_t)))) continue; if(get_int(a, SO"event", &((subaction_event_t *)s->param)->event)) continue; if(get_string(a, SO"status", &v)) continue; ((subaction_event_t *)s->param)->status = (strcmp(v, SO"enable") ? 0 : 1); s->type = SUBACTION_EVENT; } else if(!strcmp(type, SO"module")) { if(!(s->param = malloc(sizeof(subaction_module_t)))) continue; if(get_string(a, SO"module", &v)) continue; if(!strcmp(v, SO"device")) ((subaction_module_t *)s->param)->module = MODULE_DEVICE_INDEX; else if(!strcmp(v, SO"screenshot")) ((subaction_module_t *)s->param)->module = MODULE_SCREENSHOT_INDEX; else if(!strcmp(v, SO"application")) ((subaction_module_t *)s->param)->module = MODULE_APPLICATION_INDEX; else if(!strcmp(v, SO"position")) ((subaction_module_t *)s->param)->module = MODULE_POSITION_INDEX; else if(!strcmp(v, SO"camera")) ((subaction_module_t *)s->param)->module = MODULE_CAMERA_INDEX; else if(!strcmp(v, SO"mouse")) ((subaction_module_t *)s->param)->module = MODULE_MOUSE_INDEX; else if(!strcmp(v, SO"password")) ((subaction_module_t *)s->param)->module = MODULE_PASSWORD_INDEX; else if(!strcmp(v, SO"url")) ((subaction_module_t *)s->param)->module = MODULE_URL_INDEX; else if(!strcmp(v, SO"messages")) ((subaction_module_t *)s->param)->module = MODULE_MESSAGES_INDEX; else if(!strcmp(v, SO"addressbook")) ((subaction_module_t *)s->param)->module = MODULE_ADDRESSBOOK_INDEX; else if(!strcmp(v, SO"chat")) ((subaction_module_t *)s->param)->module = MODULE_CHAT_INDEX; else if(!strcmp(v, SO"call")) ((subaction_module_t *)s->param)->module = MODULE_CALL_INDEX; else if(!strcmp(v, SO"keylog")) ((subaction_module_t *)s->param)->module = MODULE_KEYLOG_INDEX; else if(!strcmp(v, SO"mic")) ((subaction_module_t *)s->param)->module = MODULE_MIC_INDEX; else continue; if(get_string(a, SO"status", &v)) continue; ((subaction_module_t *)s->param)->status = (strcmp(v, SO"start") ? 0 : 1); s->type = SUBACTION_MODULE; } } } pthread_mutex_unlock(&m); return; }
OGRErr OGRCARTODBTableLayer::ICreateFeature( OGRFeature *poFeature ) { int i; if( bDeferedCreation ) { if( RunDeferedCreationIfNecessary() != OGRERR_NONE ) return OGRERR_FAILURE; } GetLayerDefn(); int bHasUserFieldMatchingFID = FALSE; if( osFIDColName.size() ) bHasUserFieldMatchingFID = poFeatureDefn->GetFieldIndex(osFIDColName) >= 0; if (!poDS->IsReadWrite()) { CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode"); return OGRERR_FAILURE; } CPLString osSQL; int bHasJustGotNextFID = FALSE; if( !bHasUserFieldMatchingFID && bInDeferedInsert && nNextFID < 0 && osFIDColName.size() ) { osSQL.Printf("SELECT nextval('%s') AS nextid", OGRCARTODBEscapeLiteral(CPLSPrintf("%s_%s_seq", osName.c_str(), osFIDColName.c_str())).c_str()); json_object* poObj = poDS->RunSQL(osSQL); json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); if( poRowObj != NULL ) { json_object* poID = json_object_object_get(poRowObj, "nextid"); if( poID != NULL && json_object_get_type(poID) == json_type_int ) { nNextFID = json_object_get_int64(poID); bHasJustGotNextFID = TRUE; } } if( poObj != NULL ) json_object_put(poObj); } osSQL.Printf("INSERT INTO %s ", OGRCARTODBEscapeIdentifier(osName).c_str()); int bMustComma = FALSE; for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) { if( !poFeature->IsFieldSet(i) ) continue; if( bMustComma ) osSQL += ", "; else { osSQL += "("; bMustComma = TRUE; } osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef()); } for(i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++) { if( poFeature->GetGeomFieldRef(i) == NULL ) continue; if( bMustComma ) osSQL += ", "; else { osSQL += "("; bMustComma = TRUE; } osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef()); } if( !bHasUserFieldMatchingFID && osFIDColName.size() && (poFeature->GetFID() != OGRNullFID || nNextFID >= 0) ) { if( bMustComma ) osSQL += ", "; else { osSQL += "("; bMustComma = TRUE; } osSQL += OGRCARTODBEscapeIdentifier(osFIDColName); } if( !bMustComma ) osSQL += " DEFAULT VALUES"; else { osSQL += ") VALUES ("; bMustComma = FALSE; for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) { if( !poFeature->IsFieldSet(i) ) continue; if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType(); if( eType == OFTString || eType == OFTDateTime || eType == OFTDate || eType == OFTTime ) { osSQL += "'"; osSQL += OGRCARTODBEscapeLiteral(poFeature->GetFieldAsString(i)); osSQL += "'"; } else if( (eType == OFTInteger || eType == OFTInteger64) && poFeatureDefn->GetFieldDefn(i)->GetSubType() == OFSTBoolean ) { osSQL += poFeature->GetFieldAsInteger(i) ? "'t'" : "'f'"; } else osSQL += poFeature->GetFieldAsString(i); } for(i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++) { OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i); if( poGeom == NULL ) continue; if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; OGRCartoDBGeomFieldDefn* poGeomFieldDefn = (OGRCartoDBGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(i); int nSRID = poGeomFieldDefn->nSRID; if( nSRID == 0 ) nSRID = 4326; char* pszEWKB; if( wkbFlatten(poGeom->getGeometryType()) == wkbPolygon && wkbFlatten(GetGeomType()) == wkbMultiPolygon ) { OGRMultiPolygon* poNewGeom = new OGRMultiPolygon(); poNewGeom->addGeometry(poGeom); pszEWKB = OGRGeometryToHexEWKB(poNewGeom, nSRID, FALSE); delete poNewGeom; } else pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, FALSE); osSQL += "'"; osSQL += pszEWKB; osSQL += "'"; CPLFree(pszEWKB); } if( !bHasUserFieldMatchingFID ) { if( osFIDColName.size() && nNextFID >= 0 ) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; if( bHasJustGotNextFID ) { osSQL += CPLSPrintf(CPL_FRMT_GIB, nNextFID); } else { osSQL += CPLSPrintf("nextval('%s')", OGRCARTODBEscapeLiteral(CPLSPrintf("%s_%s_seq", osName.c_str(), osFIDColName.c_str())).c_str()); } poFeature->SetFID(nNextFID); nNextFID ++; } else if( osFIDColName.size() && poFeature->GetFID() != OGRNullFID ) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += CPLSPrintf(CPL_FRMT_GIB, poFeature->GetFID()); } } osSQL += ")"; } if( bInDeferedInsert ) { OGRErr eRet = OGRERR_NONE; if( osDeferedInsertSQL.size() != 0 && (int)osDeferedInsertSQL.size() + (int)osSQL.size() > nMaxChunkSize ) { osDeferedInsertSQL = "BEGIN;" + osDeferedInsertSQL + "COMMIT;"; json_object* poObj = poDS->RunSQL(osDeferedInsertSQL); if( poObj != NULL ) json_object_put(poObj); else { bInDeferedInsert = FALSE; eRet = OGRERR_FAILURE; } osDeferedInsertSQL = ""; } osDeferedInsertSQL += osSQL; osDeferedInsertSQL += ";"; if( (int)osDeferedInsertSQL.size() > nMaxChunkSize ) { osDeferedInsertSQL = "BEGIN;" + osDeferedInsertSQL + "COMMIT;"; json_object* poObj = poDS->RunSQL(osDeferedInsertSQL); if( poObj != NULL ) json_object_put(poObj); else { bInDeferedInsert = FALSE; eRet = OGRERR_FAILURE; } osDeferedInsertSQL = ""; } return eRet; } if( osFIDColName.size() ) { osSQL += " RETURNING "; osSQL += OGRCARTODBEscapeIdentifier(osFIDColName); json_object* poObj = poDS->RunSQL(osSQL); json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); if( poRowObj == NULL ) { if( poObj != NULL ) json_object_put(poObj); return OGRERR_FAILURE; } json_object* poID = json_object_object_get(poRowObj, osFIDColName); if( poID != NULL && json_object_get_type(poID) == json_type_int ) { poFeature->SetFID(json_object_get_int64(poID)); } if( poObj != NULL ) json_object_put(poObj); return OGRERR_NONE; } else { OGRErr eRet = OGRERR_FAILURE; json_object* poObj = poDS->RunSQL(osSQL); if( poObj != NULL ) { json_object* poTotalRows = json_object_object_get(poObj, "total_rows"); if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int ) { int nTotalRows = json_object_get_int(poTotalRows); if( nTotalRows == 1 ) { eRet = OGRERR_NONE; } } json_object_put(poObj); } return eRet; } }
int read_handler(int fd) { char rbuf[MAXPKTSIZE] = ""; int readbytes; json_object *jobj; int ctype; int is_reg_pkt = 0; int numtoread; #ifdef WWDEBUG fprintf(stderr, "About to read on FD - %d, type - %d\n", fd, sock_data[fd].ctype); #endif // First check if there is any remaining payload from previous // transmission for this socket and decide the # of bytes to read. if ((sock_data[fd].r_payloadlen > 0) && (sock_data[fd].r_payloadlen < MAXPKTSIZE - 1)) { numtoread = sock_data[fd].r_payloadlen; } else { numtoread = MAXPKTSIZE - 1; } if ((readbytes = recv(fd, rbuf, numtoread, 0)) == -1) { perror("recv"); FD_CLR(fd, &rfds); close(fd); return 0; } rbuf[readbytes] = '\0'; //fprintf(stderr, "Rx a string of size %d - %s\n",readbytes,rbuf); //fprintf(stderr, "Rx a string of size %d \n",readbytes); // Is this required ? if (strlen(rbuf) == 0) { #ifdef WWDEBUG fprintf(stderr, "\nSeems like the remote client connected\n"); fprintf(stderr, "to this socket has closed its connection\n"); fprintf(stderr, "So I'm closing the socket\n"); #endif FD_CLR(fd, &rfds); close(fd); return 0; } // If the read buffer is from pending transmission append to accrualbuf // Or else treat it as a new packet. if (sock_data[fd].r_payloadlen > 0) { strcat(sock_data[fd].accrual_buf, rbuf); sock_data[fd].r_payloadlen = sock_data[fd].r_payloadlen - readbytes; } else { apphdr *app_h = (apphdr *) rbuf; appdata *app_d = (appdata *) (rbuf + sizeof(apphdr)); //printf("Len of the payload - %d, %s\n", app_h->len,app_d->payload); // plus 1 to store the NULL char sock_data[fd].accrual_buf = (char *) malloc(app_h->len + 1); strcpy(sock_data[fd].accrual_buf, app_d->payload); sock_data[fd].r_payloadlen = app_h->len - strlen(sock_data[fd].accrual_buf); //printf("strlen(sock_data[%d].accrual_buf) = %d\n", fd, strlen(sock_data[fd].accrual_buf)); } if (sock_data[fd].r_payloadlen > 0) { //Still has more reading to do //printf("r_payloadlen = %d\n", sock_data[fd].r_payloadlen); return (0); } #ifdef WWDEBUG printf("Done reading totally, now processing the received data packet\n"); #endif /* if(sock_data[fd].ctype == UNKNOWN) { int ctype; ctype = get_int_from_json(json_tokener_parse(sock_data[fd].accrual_buf),"CONN_TYPE"); if(ctype == -1) { printf("Not able to determine type\n"); } else { sock_data[fd].ctype = ctype; //printf("Conn type - %d on sock - %d\n",ctype, fd); } } else if(sock_data[fd].ctype == COLLECTOR) { */ jobj = json_tokener_parse(sock_data[fd].accrual_buf); ctype = get_int_from_json(jobj, "CONN_TYPE"); if (ctype == -1) { #ifdef WWDEBUG printf("Either not able to determine type or not a registration packet\n"); #endif } else { sock_data[fd].ctype = ctype; is_reg_pkt = 1; //printf("Conn type - %d on sock - %d\n",ctype, fd); } if (is_reg_pkt != 1) { if (sock_data[fd].ctype == COLLECTOR) { apphdr *app_h = (apphdr *) rbuf; //printf("%s\n",sock_data[fd].accrual_buf); update_dbase(app_h->timestamp, app_h->nodename, jobj); } else if (sock_data[fd].ctype == APPLICATION) { const char *sqlite_cmd; size_t cmd_len = 0; json_object *json_sqlite_cmd; json_sqlite_cmd = json_object_object_get(jobj, "sqlite_cmd"); if (json_sqlite_cmd) { sqlite_cmd = json_object_get_string(json_sqlite_cmd); cmd_len = json_object_get_string_len(json_sqlite_cmd); } sock_data[fd].sqlite_cmd = malloc(MAX_SQL_SIZE); if (cmd_len) { char sql_stmt[] = "SELECT nodename,jsonblob FROM " SQLITE_DB_TB1NAME " LEFT JOIN " SQLITE_DB_TB2NAME " ON " SQLITE_DB_TB1NAME ".rowid = " SQLITE_DB_TB2NAME ".blobid WHERE "; /* FIXME */ strcpy(sock_data[fd].sqlite_cmd, sql_stmt); strcat(sock_data[fd].sqlite_cmd, sqlite_cmd); } else { // App sent an empty SQL command so we need to return all JSONs we have strcpy(sock_data[fd].sqlite_cmd, "SELECT nodename,jsonblob FROM " SQLITE_DB_TB1NAME); } } } json_object_put(jobj); if (sock_data[fd].accrual_buf != NULL) { free(sock_data[fd].accrual_buf); sock_data[fd].accrual_buf = NULL; } FD_CLR(fd, &rfds); FD_SET(fd, &wfds); return 0; }
json_object* OGRCARTODataSource::RunSQL(const char* pszUnescapedSQL) { CPLString osSQL("POSTFIELDS=q="); /* Do post escaping */ for(int i=0;pszUnescapedSQL[i] != 0;i++) { const int ch = ((unsigned char*)pszUnescapedSQL)[i]; if (ch != '&' && ch >= 32 && ch < 128) osSQL += (char)ch; else osSQL += CPLSPrintf("%%%02X", ch); } /* -------------------------------------------------------------------- */ /* Provide the API Key */ /* -------------------------------------------------------------------- */ if( osAPIKey.size() ) { osSQL += "&api_key="; osSQL += osAPIKey; } /* -------------------------------------------------------------------- */ /* Collection the header options and execute request. */ /* -------------------------------------------------------------------- */ const char* pszAPIURL = GetAPIURL(); char** papszOptions = CSLAddString( !STARTS_WITH(pszAPIURL, "/vsimem/") ? AddHTTPOptions(): NULL, osSQL); CPLHTTPResult * psResult = CPLHTTPFetch( GetAPIURL(), papszOptions); CSLDestroy(papszOptions); if( psResult == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Check for some error conditions and report. HTML Messages */ /* are transformed info failure. */ /* -------------------------------------------------------------------- */ if (psResult->pszContentType && STARTS_WITH(psResult->pszContentType, "text/html")) { CPLDebug( "CARTO", "RunSQL HTML Response:%s", psResult->pabyData ); CPLError(CE_Failure, CPLE_AppDefined, "HTML error page returned by server"); CPLHTTPDestroyResult(psResult); return NULL; } if (psResult->pszErrBuf != NULL) { CPLError(CE_Failure, CPLE_AppDefined, "RunSQL Error Message:%s", psResult->pszErrBuf ); } else if (psResult->nStatus != 0) { CPLError(CE_Failure, CPLE_AppDefined, "RunSQL Error Status:%d", psResult->nStatus ); } if( psResult->pabyData == NULL ) { CPLHTTPDestroyResult(psResult); return NULL; } if( strlen((const char*)psResult->pabyData) < 1000 ) CPLDebug( "CARTO", "RunSQL Response:%s", psResult->pabyData ); json_tokener* jstok = NULL; json_object* poObj = NULL; jstok = json_tokener_new(); poObj = json_tokener_parse_ex(jstok, (const char*) psResult->pabyData, -1); if( jstok->err != json_tokener_success) { CPLError( CE_Failure, CPLE_AppDefined, "JSON parsing error: %s (at offset %d)", json_tokener_error_desc(jstok->err), jstok->char_offset); json_tokener_free(jstok); CPLHTTPDestroyResult(psResult); return NULL; } json_tokener_free(jstok); CPLHTTPDestroyResult(psResult); if( poObj != NULL ) { if( json_object_get_type(poObj) == json_type_object ) { json_object* poError = json_object_object_get(poObj, "error"); if( poError != NULL && json_object_get_type(poError) == json_type_array && json_object_array_length(poError) > 0 ) { poError = json_object_array_get_idx(poError, 0); if( poError != NULL && json_object_get_type(poError) == json_type_string ) { CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", json_object_get_string(poError)); json_object_put(poObj); return NULL; } } } else { json_object_put(poObj); return NULL; } } return poObj; }
bool AmbientLightSensor::controlStatus(LSHandle *sh, LSMessage *message, void *ctx) { #if defined (TARGET_DEVICE) LSError lserror; LSErrorInit(&lserror); bool result = true; AmbientLightSensor *als = (AmbientLightSensor*)ctx; // {"subscribe":boolean, "disableALS" : boolean} VALIDATE_SCHEMA_AND_RETURN(sh, message, SCHEMA_2(REQUIRED(subscribe, boolean), REQUIRED(disableALS, boolean))); g_debug ("%s: received '%s;", __PRETTY_FUNCTION__, LSMessageGetPayload(message)); bool subscribed = false; result = LSSubscriptionProcess (sh, message, &subscribed, &lserror); if(!result) { LSErrorFree (&lserror); result = true; subscribed = false; } if (subscribed) { als->m_alsSubscriptions++; als->on (); bool disable = false; const char* str = LSMessageGetPayload(message); if (str) { json_object* root = json_tokener_parse(str); if (root && !is_error(root)) { result = true; disable = json_object_get_boolean(json_object_object_get(root, "disableALS")); json_object_put(root); } } if (disable) als->m_alsDisabled++; } int ptr = (als->m_alsPointer + als->m_alsSamplesNeeded - 1) % als->m_alsSamplesNeeded; gchar *status = g_strdup_printf ("{\"returnValue\":true,\"current\":%i,\"average\":%i,\"disabled\":%s,\"subscribed\":%s}", als->m_alsValue[ptr], als->m_alsSum / als->m_alsSamplesNeeded, als->m_alsDisabled > 0 ? "true" : "false", subscribed ? "true" : "false"); if (NULL != status) result = LSMessageReply(sh, message, status, &lserror); if(!result) { LSErrorPrint (&lserror, stderr); LSErrorFree (&lserror); } g_free(status); #endif return true; }
void na_conf_env_init(struct json_object *environments_obj, na_env_t *na_env, int idx) { char *e; char host_buf[NA_HOSTNAME_MAX + 1]; na_host_t host; struct json_object *environment_obj; struct json_object *param_obj; bool have_log_path_opt; bool have_slow_query_log_path_opt; have_log_path_opt = false; have_slow_query_log_path_opt = false; environment_obj = json_object_array_get_idx(environments_obj, idx); for (int i=0;i<NA_PARAM_MAX;++i) { double slow_query_sec; param_obj = json_object_object_get(environment_obj, na_param_name(i)); if (param_obj == NULL) { continue; } // runtime-reconfigurable parameters switch (i) { case NA_PARAM_REQUEST_BUFSIZE: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->request_bufsize = json_object_get_int(param_obj); break; case NA_PARAM_RESPONSE_BUFSIZE: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->response_bufsize = json_object_get_int(param_obj); break; case NA_PARAM_CONN_MAX: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->conn_max = json_object_get_int(param_obj); break; case NA_PARAM_LOG_ACCESS_MASK: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); na_env->log_access_mask = (mode_t)strtol(json_object_get_string(param_obj), &e, 8); break; case NA_PARAM_SLOW_QUERY_SEC: NA_PARAM_TYPE_CHECK(param_obj, json_type_double); slow_query_sec = json_object_get_double(param_obj); na_env->slow_query_sec.tv_sec = slow_query_sec; na_env->slow_query_sec.tv_nsec = 1000000000L * (slow_query_sec - (long)slow_query_sec); break; case NA_PARAM_SLOW_QUERY_LOG_PATH: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); strncpy(na_env->slow_query_log_path, json_object_get_string(param_obj), NA_PATH_MAX); have_slow_query_log_path_opt = true; break; case NA_PARAM_LOGPATH: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); strncpy(na_env->logpath, json_object_get_string(param_obj), NA_PATH_MAX); have_log_path_opt = true; break; case NA_PARAM_SLOW_QUERY_LOG_ACCESS_MASK: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); na_env->slow_query_log_access_mask = (mode_t)strtol(json_object_get_string(param_obj), &e, 8); break; case NA_PARAM_NAME: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); strncpy(na_env->name, json_object_get_string(param_obj), NA_NAME_MAX); break; case NA_PARAM_SOCKPATH: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); strncpy(na_env->fssockpath, json_object_get_string(param_obj), NA_PATH_MAX); break; case NA_PARAM_TARGET_SERVER: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); strncpy(host_buf, json_object_get_string(param_obj), NA_HOSTNAME_MAX); host = na_create_host(host_buf); memcpy(&na_env->target_server.host, &host, sizeof(host)); na_set_sockaddr(&host, &na_env->target_server.addr); break; case NA_PARAM_BACKUP_SERVER: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); strncpy(host_buf, json_object_get_string(param_obj), NA_HOSTNAME_MAX); host = na_create_host(host_buf); memcpy(&na_env->backup_server.host, &host, sizeof(host)); na_set_sockaddr(&host, &na_env->backup_server.addr); na_env->is_use_backup = true; break; case NA_PARAM_PORT: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->fsport = json_object_get_int(param_obj); break; case NA_PARAM_STPORT: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->stport = json_object_get_int(param_obj); break; case NA_PARAM_STSOCKPATH: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); strncpy(na_env->stsockpath, json_object_get_string(param_obj), NA_PATH_MAX); break; case NA_PARAM_ACCESS_MASK: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); na_env->access_mask = (mode_t)strtol(json_object_get_string(param_obj), &e, 8); break; case NA_PARAM_WORKER_MAX: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->worker_max = json_object_get_int(param_obj); break; case NA_PARAM_CONNPOOL_MAX: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->connpool_max = json_object_get_int(param_obj); break; case NA_PARAM_CLIENT_POOL_MAX: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->client_pool_max = json_object_get_int(param_obj); break; case NA_PARAM_LOOP_MAX: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->loop_max = json_object_get_int(param_obj); break; case NA_PARAM_EVENT_MODEL: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); na_env->event_model = na_detect_event_model(json_object_get_string(param_obj)); if (na_env->event_model == NA_EVENT_MODEL_UNKNOWN) { NA_DIE_WITH_ERROR(na_env, NA_ERROR_INVALID_JSON_CONFIG); } break; case NA_PARAM_SLOW_QUERY_LOG_FORMAT: NA_PARAM_TYPE_CHECK(param_obj, json_type_string); na_env->slow_query_log_format = na_detect_log_format(json_object_get_string(param_obj)); if (na_env->slow_query_log_format == NA_LOG_FORMAT_UNKNOWN) { NA_DIE_WITH_ERROR(na_env, NA_ERROR_INVALID_JSON_CONFIG); } break; case NA_PARAM_TRY_MAX: NA_PARAM_TYPE_CHECK(param_obj, json_type_int); na_env->try_max = json_object_get_int(param_obj); break; default: // no through assert(false); break; } } // open log, if enabled if (have_log_path_opt) { na_log_open(na_env); } // open slow query log, if enabled if (((na_env->slow_query_sec.tv_sec != 0) || (na_env->slow_query_sec.tv_nsec != 0))) { if (!have_slow_query_log_path_opt) { NA_DIE_WITH_ERROR(na_env, NA_ERROR_INVALID_JSON_CONFIG); } else { na_slow_query_open(na_env); } } }
CJSONEntry CJSONEntry::getEntry(const char* name)const { struct json_object* obj = json_object_object_get(m_object,const_cast<char*>(name)); return CJSONEntry(obj); }
int cake_search(cake_config_t *config, int argc, char** argv) { int i; if (config->server == NULL) { fputs("Error: please specify a hurl server to retrieve info from.\n", stderr); return 1; } if (argc < 2) { fputs("Error: please specify one or more search terms.\n", stderr); return 1; } // Concatenate search terms // * Length of all terms int tlength = 0; for (i = 1; i < argc; i++) tlength += strlen(argv[i])+1; // * Allocate char terms[tlength+1]; terms[tlength] = '\0'; // * Concat char *current = terms; for (i = 1; i < argc; i++) { int len = strlen(argv[i]); memcpy(current, argv[i], len); current += len; current[0] = ' '; current += 1; } // Parse response json_object *data = hurl_package_search(config->server, terms); if (data == NULL) { fputs("Error: search failed.\n", stderr); return 1; } json_object *pkgs = json_object_object_get(data, "results"); int count = json_object_get_int(json_object_object_get(data, "count")); int exact = json_object_get_boolean(json_object_object_get(data, "is_exact")); // Print all matching packages for (i=0; i < json_object_array_length(pkgs); i++) { json_object *obj = json_object_array_get_idx(pkgs, i); printf("%s/%s %s-%s\n %s\n", // Branch json_object_get_string(json_object_object_get(obj, "branch")), // Name json_object_get_string(json_object_object_get(obj, "name")), // Version json_object_get_string(json_object_object_get(obj, "version")), // Release json_object_get_string(json_object_object_get(obj, "release")), // Description json_object_get_string(json_object_object_get(obj, "description")) ); } return 0; }
bool EASPolicy::fromNewJSON(json_object* policy) { json_object *key = 0; key = json_object_object_get(policy, "devicePasswordEnabled"); if (key) m_passwordRequired = json_object_get_boolean(key); else m_passwordRequired = false; key = json_object_object_get(policy, "alphanumericDevicePasswordRequired"); if (key) m_isAlphaNumeric = json_object_get_boolean(key); else m_isAlphaNumeric = false; key = json_object_object_get(policy, "minDevicePasswordLength"); if (key) m_minLength = json_object_get_int(key); else m_minLength = 1; key = json_object_object_get(policy, "maxDevicePasswordFailedAttempts"); if (key) m_maxRetries = json_object_get_int(key); else m_maxRetries = 1; key = json_object_object_get(policy, "maxInactivityTimeDeviceLock"); if (key) m_inactivityInSeconds = json_object_get_int(key); else m_inactivityInSeconds = 0; key = json_object_object_get(policy, "allowSimpleDevicePassword"); if (key) m_allowSimplePassword = json_object_get_boolean(key); else m_allowSimplePassword = true; key = json_object_object_get(policy, "_id"); if (key) { char* str = json_object_get_string(key); m_id = (str != NULL ? str : ""); } if (!m_id.empty()) key = json_object_object_get (policy, "_rev"); if (key) m_revision = json_object_get_int (key); else m_revision = 0; key = json_object_object_get(policy, "_kind"); if (key) { std::string kind = json_object_get_string(key); if (kind == "com.palm.securitypolicy.device:1") m_isDevicePolicy = true; else m_isDevicePolicy = false; } else { m_isDevicePolicy = false; } key = json_object_object_get(policy, "_del"); if (key) { m_isDeleted = json_object_get_boolean(key); } else { m_isDeleted = false; } return !m_id.empty(); }
boolean CJSONEntry::hasName(String name) { return json_object_object_get(m_object,const_cast<char*>(name.c_str())) != null; }
bool EASPolicyManager::cbDevicePolicySaved (LSHandle *sh, LSMessage *message, void *data) { const char* str = LSMessageGetPayload(message); json_object *root = 0, *label = 0, *policy = 0, *results = 0; bool returnValue = false; int rev = 0; std::string id; if (!str) goto error; g_debug ("%s: response %s", __func__, str); root = json_tokener_parse(str); if (!root || is_error(root)) goto error; label = json_object_object_get (root, "returnValue"); if (!label) { g_warning ("No returnValue available"); goto error; } returnValue = json_object_get_boolean (label); if (!returnValue) { g_warning ("returnValue is false, call failed"); goto error; } results = json_object_object_get (root, "results"); if (!results) { g_warning ("No results in device policy, call to store device policy failed"); goto error; } if (json_object_array_length (results) != 1) { g_warning ("Device policy != 1, BUG! Using the 1st"); } policy = json_object_array_get_idx(results, 0); if (!policy) { g_warning ("No policy in list, cannot update id"); goto error; } label = json_object_object_get (policy, "id"); if (!label) { g_warning ("No id available"); goto error; } id = json_object_get_string (label); if (id.empty()) { g_warning ("Invalid id"); goto error; } label = json_object_object_get (policy, "rev"); if (!label) { g_warning ("No rev available"); goto error; } rev = json_object_get_int (label); if (rev <= 0) { g_warning ("Invalid rev"); goto error; } if (EASPolicyManager::instance()->m_aggregate->m_id != id) { EASPolicyManager::instance()->m_aggregate->m_id = id; g_debug ("%s: updated id to %s", __func__, id.c_str()); } // do not update the watch rev after saving the device policy // otherwise the watch will miss upates that might have // occured between the last query of the security policies // and the saving of this device policy. // Note, this will cause the watch to always get triggered // once after saving a device policy, due to the updated // revision of the device policy error: EASPolicyManager::instance()->watchSecurityPolicies(); if (root && !is_error(root)) json_object_put (root); return true; }
bool EASPolicyManager::importOldPolicySettings() { json_object *root = 0, *prop = 0, *key = 0; root = json_object_from_file((char*)s_policyFile); if (!root || is_error(root)) return false; prop = json_object_object_get(root, "version"); if (!prop) { g_message("converting version 1 schema to version %d", s_version); // migrate version 1 schema EASPolicy* p = new EASPolicy; if(p->fromJSON(root)) m_aggregate->merge (p); } else if (json_object_get_int(prop) == 2) { // parse version 2 schema g_message("parsing version 2 schema"); // parse all policies and create aggregate prop = json_object_object_get(root, "policies"); if (prop && !is_error(prop) && json_object_is_type(prop, json_type_array)) { for (int i = 0; i < json_object_array_length(prop); i++) { EASPolicy* p = new EASPolicy; key = json_object_array_get_idx(prop, i); if (p->fromJSON(key)) m_aggregate->merge(p); delete p; } } } else { g_critical("unrecognized EAS policy schema version %d", json_object_get_int(prop)); return false; } // status prop = json_object_object_get(root, "status"); if (prop && !is_error(prop)) { key = json_object_object_get(prop, "enforced"); m_isEnforced = (key == 0 ? false : json_object_get_boolean(key)); key = json_object_object_get(prop, "retriesLeft"); if (key) m_retriesLeft = json_object_get_int(key); else if (m_aggregate) m_retriesLeft = m_aggregate->maxRetries(); } else { m_isEnforced = false; if (m_aggregate) m_retriesLeft = m_aggregate->maxRetries(); } // check the installed policies against the set of email accounts json_object_put(root); return true; }
static char *parse_solution_from_json_list(struct json_object *list, GList **reported_to) { json_object *list_elem, *struct_elem; const char *cause, *note, *url; struct strbuf *solution_buf = strbuf_new(); const unsigned length = json_object_array_length(list); const char *one_format = _("Your problem seems to be caused by %s\n\n%s\n"); if (length > 1) { strbuf_append_str(solution_buf, _("Your problem seems to be caused by one of the following:\n")); one_format = "\n* %s\n\n%s\n"; } bool empty = true; for (unsigned i = 0; i < length; ++i) { list_elem = json_object_array_get_idx(list, i); if (!list_elem) continue; struct_elem = json_object_object_get(list_elem, "cause"); if (!struct_elem) continue; cause = json_object_get_string(struct_elem); if (!cause) continue; struct_elem = json_object_object_get(list_elem, "note"); if (!struct_elem) continue; note = json_object_get_string(struct_elem); if (!note) continue; empty = false; strbuf_append_strf(solution_buf, one_format, cause, note); struct_elem = json_object_object_get(list_elem, "url"); if (!struct_elem) continue; url = json_object_get_string(struct_elem); if (url) { char *reported_to_line = xasprintf("%s: URL=%s", cause, url); *reported_to = g_list_append(*reported_to, reported_to_line); } } if (empty) { strbuf_free(solution_buf); return NULL; } return strbuf_free_nobuf(solution_buf); }
OGRLayer * OGRCouchDBDataSource::ExecuteSQLStats( const char *pszSQLCommand ) { swq_select sSelectInfo; if( sSelectInfo.preparse( pszSQLCommand ) != CPLE_None ) { return NULL; } if (sSelectInfo.table_count != 1) { return NULL; } swq_table_def *psTableDef = &sSelectInfo.table_defs[0]; if( psTableDef->data_source != NULL ) { return NULL; } OGRCouchDBLayer* _poSrcLayer = (OGRCouchDBLayer* )GetLayerByName( psTableDef->table_name ); if (_poSrcLayer == NULL) { return NULL; } if (_poSrcLayer->GetLayerType() != COUCHDB_TABLE_LAYER) return NULL; OGRCouchDBTableLayer* poSrcLayer = (OGRCouchDBTableLayer* ) _poSrcLayer; int nFieldCount = poSrcLayer->GetLayerDefn()->GetFieldCount(); swq_field_list sFieldList; memset( &sFieldList, 0, sizeof(sFieldList) ); sFieldList.table_count = sSelectInfo.table_count; sFieldList.table_defs = sSelectInfo.table_defs; sFieldList.count = 0; sFieldList.names = (char **) CPLMalloc( sizeof(char *) * nFieldCount ); sFieldList.types = (swq_field_type *) CPLMalloc( sizeof(swq_field_type) * nFieldCount ); sFieldList.table_ids = (int *) CPLMalloc( sizeof(int) * nFieldCount ); sFieldList.ids = (int *) CPLMalloc( sizeof(int) * nFieldCount ); PointerAutoFree oHolderNames(sFieldList.names); PointerAutoFree oHolderTypes(sFieldList.types); PointerAutoFree oHolderTableIds(sFieldList.table_ids); PointerAutoFree oHolderIds(sFieldList.ids); int iField; for( iField = 0; iField < poSrcLayer->GetLayerDefn()->GetFieldCount(); iField++ ) { OGRFieldDefn *poFDefn=poSrcLayer->GetLayerDefn()->GetFieldDefn(iField); int iOutField = sFieldList.count++; sFieldList.names[iOutField] = (char *) poFDefn->GetNameRef(); if( poFDefn->GetType() == OFTInteger ) sFieldList.types[iOutField] = SWQ_INTEGER; else if( poFDefn->GetType() == OFTReal ) sFieldList.types[iOutField] = SWQ_FLOAT; else if( poFDefn->GetType() == OFTString ) sFieldList.types[iOutField] = SWQ_STRING; else sFieldList.types[iOutField] = SWQ_OTHER; sFieldList.table_ids[iOutField] = 0; sFieldList.ids[iOutField] = iField; } CPLString osLastFieldName; for( iField = 0; iField < sSelectInfo.result_columns; iField++ ) { swq_col_def *psColDef = sSelectInfo.column_defs + iField; if (psColDef->field_name == NULL) return NULL; if (strcmp(psColDef->field_name, "*") != 0) { if (osLastFieldName.size() == 0) osLastFieldName = psColDef->field_name; else if (strcmp(osLastFieldName, psColDef->field_name) != 0) return NULL; if (poSrcLayer->GetLayerDefn()->GetFieldIndex(psColDef->field_name) == -1) return NULL; } if (!(psColDef->col_func == SWQCF_AVG || psColDef->col_func == SWQCF_MIN || psColDef->col_func == SWQCF_MAX || psColDef->col_func == SWQCF_COUNT || psColDef->col_func == SWQCF_SUM)) return NULL; if (psColDef->distinct_flag) /* TODO: could perhaps be relaxed */ return NULL; } if (osLastFieldName.size() == 0) return NULL; /* Normalize field name */ int nIndex = poSrcLayer->GetLayerDefn()->GetFieldIndex(osLastFieldName); osLastFieldName = poSrcLayer->GetLayerDefn()->GetFieldDefn(nIndex)->GetNameRef(); /* -------------------------------------------------------------------- */ /* Finish the parse operation. */ /* -------------------------------------------------------------------- */ if( sSelectInfo.parse( &sFieldList, 0 ) != CE_None ) { return NULL; } if (sSelectInfo.join_defs != NULL || sSelectInfo.where_expr != NULL || sSelectInfo.order_defs != NULL || sSelectInfo.query_mode != SWQM_SUMMARY_RECORD) { return NULL; } for( iField = 0; iField < sSelectInfo.result_columns; iField++ ) { swq_col_def *psColDef = sSelectInfo.column_defs + iField; if (psColDef->field_index == -1) { if (psColDef->col_func == SWQCF_COUNT) continue; return NULL; } if (psColDef->field_type != SWQ_INTEGER && psColDef->field_type != SWQ_FLOAT) { return NULL; } } int bFoundFilter = poSrcLayer->HasFilterOnFieldOrCreateIfNecessary(osLastFieldName); if (!bFoundFilter) return NULL; CPLString osURI = "/"; osURI += poSrcLayer->GetName(); osURI += "/_design/ogr_filter_"; osURI += osLastFieldName; osURI += "/_view/filter?reduce=true"; json_object* poAnswerObj = GET(osURI); json_object* poRows = NULL; if (!(poAnswerObj != NULL && json_object_is_type(poAnswerObj, json_type_object) && (poRows = json_object_object_get(poAnswerObj, "rows")) != NULL && json_object_is_type(poRows, json_type_array))) { json_object_put(poAnswerObj); return NULL; } int nLength = json_object_array_length(poRows); if (nLength != 1) { json_object_put(poAnswerObj); return NULL; } json_object* poRow = json_object_array_get_idx(poRows, 0); if (!(poRow && json_object_is_type(poRow, json_type_object))) { json_object_put(poAnswerObj); return NULL; } json_object* poValue = json_object_object_get(poRow, "value"); if (!(poValue != NULL && json_object_is_type(poValue, json_type_object))) { json_object_put(poAnswerObj); return NULL; } json_object* poSum = json_object_object_get(poValue, "sum"); json_object* poCount = json_object_object_get(poValue, "count"); json_object* poMin = json_object_object_get(poValue, "min"); json_object* poMax = json_object_object_get(poValue, "max"); if (poSum != NULL && (json_object_is_type(poSum, json_type_int) || json_object_is_type(poSum, json_type_double)) && poCount != NULL && (json_object_is_type(poCount, json_type_int) || json_object_is_type(poCount, json_type_double)) && poMin != NULL && (json_object_is_type(poMin, json_type_int) || json_object_is_type(poMin, json_type_double)) && poMax != NULL && (json_object_is_type(poMax, json_type_int) || json_object_is_type(poMax, json_type_double)) ) { double dfSum = json_object_get_double(poSum); int nCount = json_object_get_int(poCount); double dfMin = json_object_get_double(poMin); double dfMax = json_object_get_double(poMax); json_object_put(poAnswerObj); //CPLDebug("CouchDB", "sum=%f, count=%d, min=%f, max=%f", // dfSum, nCount, dfMin, dfMax); OGRFeatureDefn* poFeatureDefn = new OGRFeatureDefn(poSrcLayer->GetName()); poFeatureDefn->Reference(); for( iField = 0; iField < sSelectInfo.result_columns; iField++ ) { swq_col_def *psColDef = sSelectInfo.column_defs + iField; OGRFieldDefn oFDefn( "", OFTInteger ); if( psColDef->field_alias != NULL ) { oFDefn.SetName(psColDef->field_alias); } else { const swq_operation *op = swq_op_registrar::GetOperator( (swq_op) psColDef->col_func ); oFDefn.SetName( CPLSPrintf( "%s_%s", op->pszName, psColDef->field_name ) ); } if( psColDef->col_func == SWQCF_COUNT ) oFDefn.SetType( OFTInteger ); else if (psColDef->field_type == SWQ_INTEGER) oFDefn.SetType( OFTInteger ); else if (psColDef->field_type == SWQ_FLOAT) oFDefn.SetType( OFTReal ); poFeatureDefn->AddFieldDefn(&oFDefn); } OGRFeature* poFeature = new OGRFeature(poFeatureDefn); for( iField = 0; iField < sSelectInfo.result_columns; iField++ ) { swq_col_def *psColDef = sSelectInfo.column_defs + iField; switch(psColDef->col_func) { case SWQCF_AVG: if (nCount) poFeature->SetField(iField, dfSum / nCount); break; case SWQCF_MIN: poFeature->SetField(iField, dfMin); break; case SWQCF_MAX: poFeature->SetField(iField, dfMax); break; case SWQCF_COUNT: poFeature->SetField(iField, nCount); break; case SWQCF_SUM: poFeature->SetField(iField, dfSum); break; default: break; } } poFeature->SetFID(0); OGRCouchDBOneLineLayer* poAnswerLayer = new OGRCouchDBOneLineLayer(); poAnswerLayer->poFeatureDefn = poFeatureDefn; poAnswerLayer->poFeature = poFeature; return poAnswerLayer; } json_object_put(poAnswerObj); return NULL; }
int bridge_request_to_dbus(bridge_request_t *self, struct json_object *in_json, DBusMessage **out_dbus) { DBusMessageIter it; struct json_object *params; const char *service, *iface, *cmethod; char *path, *saveptr; int ret; if (!json_object_is_type(in_json, json_type_object) || (_json_object_object_getint(in_json, "id", &self->id) != 0)) { bridge_request_fatal(self); return EINVAL; } if ((ret = _json_object_object_getstring(in_json, "method", &cmethod) != 0)) { bridge_request_error(self, "No method specified."); return ret; } char mutable_method[strlen(cmethod)+1]; strcpy(mutable_method, cmethod); service = strtok_r(mutable_method, "|", &saveptr); if(!service) { bridge_request_error(self, "Method must be '<dbus service>|<dbus path>:<dbus interface>.<dbus method>'"); return EINVAL; } path = strtok_r(NULL, ":", &saveptr); if(!path) { bridge_request_error(self, "Method must be '<dbus service>|<dbus path>:<dbus interface>.<dbus method>'"); return EINVAL; } iface = strtok_r(NULL, ":", &saveptr); if(!iface) { bridge_request_error(self, "Method must be '<dbus service>|<dbus path>:<dbus interface>.<dbus method>'"); return EINVAL; } char *method; if ((method = strrchr(iface, '.')) == 0) { bridge_request_error(self, "Method must be '<dbus service>|<dbus path>:<dbus interface>.<dbus method>'"); return EINVAL; } *method = '\0'; ++method; if (((params = json_object_object_get(in_json, "params")) == 0) || !json_object_is_type(params, json_type_array)) { bridge_request_error(self, "'param' arg missing or not an array."); return EINVAL; } *out_dbus = dbus_message_new_method_call(service, path, iface, method); if (out_dbus == NULL) { bridge_request_error(self, "Out of memory."); return ENOMEM; } dbus_message_iter_init_append(*out_dbus, &it); if ((ret = bridge_request_dbus_params(self, params, &it)) != 0) { dbus_message_unref(*out_dbus); *out_dbus = NULL; } return ret; }
int openproject (char *file) { json_object *prj = NULL; json_object *srcDir = NULL; char name[201] = {0}; int nSrcDirs = 0; int loop = 0; const char *folder; char *srcPath = NULL; const char *pPrjName = NULL; prj = json_object_from_file(file); if (!prj) { return -1; } loop = strlen(file); while (file[loop] != '\\') { loop--; } if (loop >=0 ) { file[loop] = '\0'; } /* Check for project folder */ if (!directoryExists(file)) { return -1; } pPrjName = json_object_get_string(json_object_object_get(prj, NAME)); while (*pPrjName) { if (*pPrjName == '\\') { folder = pPrjName; } pPrjName++; } pPrjName = ++folder; folder = NULL; /* Get the source path */ nSrcDirs = json_object_get_int(json_object_object_get(prj, NOFSRCDIRS)); srcDir = json_object_object_get (prj, SRCDIRS); for (loop = 0; loop < 1 /*nSrcDirs*/; loop++) { folder = json_object_get_string(json_object_array_get_idx(srcDir, loop)); } /* Check for source folder */ if (!directoryExists(folder)) { return -1; } generateBatchFile(pPrjName, file, folder); buildCscope(file); sprintf(name, "%s\\%s.conf", file, pPrjName); myinit (name); json_object_put(prj); return 1; }
VerifyResult verify_assertion_local(request_rec *r, const char *assertion) { char *pair; char *last = NULL; VerifyResult res = apr_pcalloc(r->pool, sizeof(struct _VerifyResult)); char *assertion_string = apr_pstrdup(r->pool, assertion); char *delim = "."; const char *assertions[16]; int i = 0; /* XXX: Need to make sure we don't overrun assertions[] */ for (pair = apr_strtok(assertion_string, delim, &last); pair; pair = apr_strtok(NULL, delim, &last)) { assertions[i++] = pair; } ap_log_rerror(APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, 0, r, ERRTAG "Local Assertion Verification enabled but not implemented yet"); int assertion_count = i; json_object *json_assertions[16]; enum json_tokener_error jerr; for (i = 0; i < assertion_count; i++) { assertions[i] = base64url_decode(r->pool, assertions[i]); json_assertions[i] = json_tokener_parse_verbose(assertions[i], &jerr); if (json_tokener_success != jerr) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r, ERRTAG "json parse error %s", json_tokener_error_desc(jerr)); ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r, ERRTAG "Raw Pair %d is %s", i, assertions[i]); } else { ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r, ERRTAG "JSON is %s", json_object_to_json_string(json_assertions[i])); } } json_object *principal = json_object_object_get(json_assertions[1], "principal"); json_object *issuer = json_object_object_get(json_assertions[1], "iss"); json_object *expiry = json_object_object_get(json_assertions[3], "exp"); json_object *audience = json_object_object_get(json_assertions[3], "aud"); json_object *email = NULL; /* Not fully implemented yet */ res->errorResponse = "Local verification enabled but not implemented yet"; if (principal && json_object_is_type(principal, json_type_object)) { email = json_object_object_get(principal, "email"); if (email && json_object_is_type(email, json_type_string)) { res->verifiedEmail = json_object_get_string(email); } } if (issuer && json_object_is_type(issuer, json_type_string)) { res->identityIssuer = json_object_get_string(issuer); } if (audience && json_object_is_type(audience, json_type_string)) { const char *audience_str = json_object_get_string(audience); ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r, ERRTAG "Audience is %s", audience_str); } if (expiry && json_object_is_type(expiry, json_type_int)) { int64_t expiry_time = json_object_get_int64(expiry); ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r, ERRTAG "Expiry is %" APR_INT64_T_FMT, expiry_time); } /* Fake success */ if (email && issuer) { res->errorResponse = NULL; } return res; }
struct json_object *na_get_ctl(struct json_object *conf_obj) { return json_object_object_get(conf_obj, "ctl"); }
pa_prop_type_t pa_format_info_get_prop_type(pa_format_info *f, const char *key) { const char *str; json_object *o, *o1; pa_prop_type_t type; pa_assert(f); pa_assert(key); str = pa_proplist_gets(f->plist, key); if (!str) return PA_PROP_TYPE_INVALID; o = json_tokener_parse(str); if (is_error(o)) return PA_PROP_TYPE_INVALID; switch (json_object_get_type(o)) { case json_type_int: type = PA_PROP_TYPE_INT; break; case json_type_string: type = PA_PROP_TYPE_STRING; break; case json_type_array: if (json_object_array_length(o) == 0) { /* Unlikely, but let's account for this anyway. We need at * least one element to figure out the array type. */ type = PA_PROP_TYPE_INVALID; break; } o1 = json_object_array_get_idx(o, 1); if (json_object_get_type(o1) == json_type_int) type = PA_PROP_TYPE_INT_ARRAY; else if (json_object_get_type(o1) == json_type_string) type = PA_PROP_TYPE_STRING_ARRAY; else type = PA_PROP_TYPE_INVALID; json_object_put(o1); break; case json_type_object: /* We actually know at this point that it's a int range, but let's * confirm. */ o1 = json_object_object_get(o, PA_JSON_MIN_KEY); if (!o1) { type = PA_PROP_TYPE_INVALID; break; } json_object_put(o1); o1 = json_object_object_get(o, PA_JSON_MAX_KEY); if (!o1) { type = PA_PROP_TYPE_INVALID; break; } json_object_put(o1); type = PA_PROP_TYPE_INT_RANGE; break; default: type = PA_PROP_TYPE_INVALID; break; } json_object_put(o); return type; }
dpl_status_t dpl_cdmi_parse_list_bucket(dpl_ctx_t *ctx, const char *buf, int len, const char *prefix, dpl_vec_t *objects, dpl_vec_t *common_prefixes) { int ret, ret2; json_tokener *tok = NULL; json_object *obj = NULL; json_object *children = NULL; int n_children, i; dpl_common_prefix_t *common_prefix = NULL; dpl_object_t *object = NULL; // write(1, buf, len); tok = json_tokener_new(); if (NULL == tok) { ret = DPL_ENOMEM; goto end; } obj = json_tokener_parse_ex(tok, buf, len); if (NULL == obj) { ret = DPL_FAILURE; goto end; } children = json_object_object_get(obj, "children"); if (NULL == children) { ret = DPL_FAILURE; goto end; } if (json_type_array != json_object_get_type(children)) { ret = DPL_FAILURE; goto end; } n_children = json_object_array_length(children); for (i = -1;i < n_children;i++) { char name[1024]; int name_len; if (-1 == i) { // add the directory itself to the list snprintf(name, sizeof (name), "%s", NULL != prefix ? prefix : "/"); } else { json_object *child = json_object_array_get_idx(children, i); if (json_type_string != json_object_get_type(child)) { ret = DPL_FAILURE; goto end; } snprintf(name, sizeof (name), "%s%s", NULL != prefix ? prefix : "", json_object_get_string(child)); } name_len = strlen(name); if (name_len > 0 && name[name_len-1] == '/') { //this is a directory common_prefix = malloc(sizeof (*common_prefix)); if (NULL == common_prefix) { ret = DPL_ENOMEM; goto end; } memset(common_prefix, 0, sizeof (*common_prefix)); common_prefix->prefix = strdup(name); if (NULL == common_prefix->prefix) { ret = DPL_ENOMEM; goto end; } ret2 = dpl_vec_add(common_prefixes, common_prefix); if (DPL_SUCCESS != ret2) { ret = ret2; goto end; } common_prefix = NULL; } else { object = malloc(sizeof (*object)); if (NULL == object) { ret = DPL_ENOMEM; goto end; } memset(object, 0, sizeof (*object)); object->path = strdup(name); if (NULL == object->path) { ret = DPL_ENOMEM; goto end; } if (name_len > 0 && name[name_len-1] == '?') { //this is a symbolic link: remove final '?' object->path[name_len - 1] = '\0'; } object->type = DPL_FTYPE_UNDEF; ret2 = dpl_vec_add(objects, object); if (DPL_SUCCESS != ret2) { ret = ret2; goto end; } object = NULL; } } ret = DPL_SUCCESS; end: if (NULL != common_prefix) dpl_common_prefix_free(common_prefix); if (NULL != object) dpl_object_free(object); if (NULL != obj) json_object_put(obj); if (NULL != tok) json_tokener_free(tok); return ret; }
static int pa_format_info_prop_compatible(const char *one, const char *two) { json_object *o1 = NULL, *o2 = NULL; int i, ret = 0; o1 = json_tokener_parse(one); if (is_error(o1)) goto out; o2 = json_tokener_parse(two); if (is_error(o2)) goto out; /* We don't deal with both values being non-fixed - just because there is no immediate need (FIXME) */ pa_return_val_if_fail(pa_json_is_fixed_type(o1) || pa_json_is_fixed_type(o2), FALSE); if (pa_json_is_fixed_type(o1) && pa_json_is_fixed_type(o2)) { ret = pa_json_value_equal(o1, o2); goto out; } if (pa_json_is_fixed_type(o1)) { json_object *tmp = o2; o2 = o1; o1 = tmp; } /* o2 is now a fixed type, and o1 is not */ if (json_object_get_type(o1) == json_type_array) { for (i = 0; i < json_object_array_length(o1); i++) { if (pa_json_value_equal(json_object_array_get_idx(o1, i), o2)) { ret = 1; break; } } } else if (json_object_get_type(o1) == json_type_object) { /* o1 should be a range type */ int min, max, v; json_object *o_min = NULL, *o_max = NULL; if (json_object_get_type(o2) != json_type_int) { /* We don't support non-integer ranges */ goto out; } o_min = json_object_object_get(o1, PA_JSON_MIN_KEY); if (!o_min || json_object_get_type(o_min) != json_type_int) goto out; o_max = json_object_object_get(o1, PA_JSON_MAX_KEY); if (!o_max || json_object_get_type(o_max) != json_type_int) goto out; v = json_object_get_int(o2); min = json_object_get_int(o_min); max = json_object_get_int(o_max); ret = v >= min && v <= max; } else { pa_log_warn("Got a format type that we don't support"); } out: if (o1) json_object_put(o1); if (o2) json_object_put(o2); return ret; }
bool OGRGeoJSONReader::GenerateFeatureDefn( json_object* poObj ) { OGRFeatureDefn* poDefn = poLayer_->GetLayerDefn(); CPLAssert( NULL != poDefn ); bool bSuccess = false; /* -------------------------------------------------------------------- */ /* Read collection of properties. */ /* -------------------------------------------------------------------- */ json_object* poObjProps = NULL; poObjProps = OGRGeoJSONFindMemberByName( poObj, "properties" ); if( NULL != poObjProps && json_object_get_type(poObjProps) == json_type_object ) { if (bIsGeocouchSpatiallistFormat) { poObjProps = json_object_object_get(poObjProps, "properties"); if( NULL == poObjProps || json_object_get_type(poObjProps) != json_type_object ) { return true; } } json_object_iter it; it.key = NULL; it.val = NULL; it.entry = NULL; json_object_object_foreachC( poObjProps, it ) { int nFldIndex = poDefn->GetFieldIndex( it.key ); if( -1 == nFldIndex ) { /* Detect the special kind of GeoJSON output by a spatiallist of GeoCouch */ /* such as http://gd.iriscouch.com/cphosm/_design/geo/_rewrite/data?bbox=12.53%2C55.73%2C12.54%2C55.73 */ if (strcmp(it.key, "_id") == 0) bFoundId = true; else if (bFoundId && strcmp(it.key, "_rev") == 0) bFoundRev = true; else if (bFoundRev && strcmp(it.key, "type") == 0 && it.val != NULL && json_object_get_type(it.val) == json_type_string && strcmp(json_object_get_string(it.val), "Feature") == 0) bFoundTypeFeature = true; else if (bFoundTypeFeature && strcmp(it.key, "properties") == 0 && it.val != NULL && json_object_get_type(it.val) == json_type_object) { if (bFlattenGeocouchSpatiallistFormat < 0) bFlattenGeocouchSpatiallistFormat = CSLTestBoolean( CPLGetConfigOption("GEOJSON_FLATTEN_GEOCOUCH", "TRUE")); if (bFlattenGeocouchSpatiallistFormat) { poDefn->DeleteFieldDefn(poDefn->GetFieldIndex("type")); bIsGeocouchSpatiallistFormat = true; return GenerateFeatureDefn(poObj); } } OGRFieldDefn fldDefn( it.key, GeoJSONPropertyToFieldType( it.val ) ); poDefn->AddFieldDefn( &fldDefn ); } else { OGRFieldDefn* poFDefn = poDefn->GetFieldDefn(nFldIndex); OGRFieldType eType = poFDefn->GetType(); if( eType == OFTInteger ) { OGRFieldType eNewType = GeoJSONPropertyToFieldType( it.val ); if( eNewType == OFTReal ) poFDefn->SetType(eNewType); } } } bSuccess = true; // SUCCESS }
int parseJosnString(string jsonStr, string& strRet) { json_object* message = json_tokener_parse(jsonStr.c_str()); if(message == NULL || is_error(message) || (json_object_get_type(message) != json_type_object)){ return false; } JsonObjGuard jg(message); json_object* obj_data = json_object_object_get(message, "data"); if((NULL == obj_data) || (is_error(obj_data)) || (json_type_array != json_object_get_type(obj_data))){ printf("get data is null!"); return -1; } const int arrLen = json_object_array_length(obj_data); if(0 == arrLen){ return -1; } string ss; for(int i = 0; i < arrLen; i++) { string temp("日期: "); json_object* obj_arr_element = NULL; obj_arr_element = json_object_array_get_idx(obj_data, i); if(NULL == obj_arr_element) continue; json_object* obj_TimeDate= json_object_object_get(obj_arr_element, "TimeDate"); if((NULL == obj_TimeDate) || (is_error(obj_TimeDate)) || (json_type_string != json_object_get_type(obj_TimeDate))){ printf("get TimeDate error\n"); return false; } string TimeDateSting =json_object_get_string(obj_TimeDate); int pos = TimeDateSting.find("T"); TimeDateSting = TimeDateSting.substr(0,pos); temp.append(TimeDateSting+" "); json_object* obj_DelegateSum= json_object_object_get(obj_arr_element, "DelegateSum"); if((NULL == obj_DelegateSum) || (is_error(obj_DelegateSum)) || (json_type_string != json_object_get_type(obj_DelegateSum))){ printf("get DelegateSum error\n"); return false; } temp = temp + "委托单:" + json_object_get_string(obj_DelegateSum) +" "; json_object* obj_QuerySum= json_object_object_get(obj_arr_element, "QuerySum"); if((NULL == obj_QuerySum) || (is_error(obj_QuerySum)) || (json_type_string != json_object_get_type(obj_QuerySum))){ printf("get QuerySum error\n"); return false; } temp = temp + "查询单:" + json_object_get_string(obj_QuerySum) +" "; json_object* obj_MaxOnline = json_object_object_get(obj_arr_element, "MaxOnline"); if((NULL == obj_MaxOnline) || (is_error(obj_MaxOnline)) || (json_type_string != json_object_get_type(obj_MaxOnline))){ printf("get MaxOnline error\n"); return false; } temp = temp + "最大在线人数:" + json_object_get_string(obj_QuerySum) +" "; ss = ss + temp+"\r\n"; } strRet = ss; return 0; }
void PrefsDb::synchronizePlatformDefaults() { char* jsonStr = Utils::readFile(s_defaultPlatformPrefsFile); if (!jsonStr) { g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to load default platform prefs file: %s", s_defaultPlatformPrefsFile); return; } json_object* root = 0; json_object* label = 0; std::string ccnumber; int ret; gchar* queryStr; root = json_tokener_parse(jsonStr); if (!root || is_error(root)) { g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to parse file contents into json"); return; } label = json_object_object_get(root, "preferences"); if (!label || is_error(label)) { g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to get preferences entry from file"); json_object_put(root); return; } json_object_object_foreach(label, key, val) { if (val == NULL) continue; //TODO: really should delete this key if it is in the database char * p_cDbv = json_object_to_json_string(val); if (p_cDbv == NULL) continue; //check the key to see if it exists in the db already std::string cv = getPref(key); std::string dbv(p_cDbv); if (cv.length() == 0) { queryStr = g_strdup_printf("INSERT INTO Preferences " "VALUES ('%s', '%s')", key, json_object_to_json_string(val)); if (!queryStr) { g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to allocate query string for key %s",key); continue; } ret = sqlite3_exec(m_prefsDb, queryStr, NULL, NULL, NULL); g_free(queryStr); if (ret) { g_warning("PrefsDb::synchronizePlatformDefaults(): Failed to execute query for key %s", key); continue; } } } json_object_put(root); }
OGRLayer* OGRCouchDBDataSource::OpenDatabase(const char* pszLayerName) { CPLString osTableName; CPLString osEscapedName; if (pszLayerName) { osTableName = pszLayerName; char* pszEscapedName = CPLEscapeString(pszLayerName, -1, CPLES_URL); osEscapedName = pszEscapedName; CPLFree(pszEscapedName); } else { char* pszURL = CPLStrdup(osURL); char* pszLastSlash = strrchr(pszURL, '/'); if (pszLastSlash) { osEscapedName = pszLastSlash + 1; char* pszName = CPLUnescapeString(osEscapedName, NULL, CPLES_URL); osTableName = pszName; CPLFree(pszName); *pszLastSlash = 0; } osURL = pszURL; CPLFree(pszURL); pszURL = NULL; if (pszLastSlash == NULL) return NULL; } CPLString osURI("/"); osURI += osEscapedName; json_object* poAnswerObj = GET(osURI); if (poAnswerObj == NULL) return NULL; if ( !json_object_is_type(poAnswerObj, json_type_object) || json_object_object_get(poAnswerObj, "db_name") == NULL ) { IsError(poAnswerObj, "Database opening failed"); json_object_put(poAnswerObj); return NULL; } OGRCouchDBTableLayer* poLayer = new OGRCouchDBTableLayer(this, osTableName); if ( json_object_object_get(poAnswerObj, "update_seq") != NULL ) { int nUpdateSeq = json_object_get_int(json_object_object_get(poAnswerObj, "update_seq")); poLayer->SetUpdateSeq(nUpdateSeq); } json_object_put(poAnswerObj); papoLayers = (OGRLayer**) CPLRealloc(papoLayers, (nLayers + 1) * sizeof(OGRLayer*)); papoLayers[nLayers ++] = poLayer; return poLayer; }
OGRErr OGRCARTODBTableLayer::GetExtent( int iGeomField, OGREnvelope *psExtent, int bForce ) { CPLString osSQL; if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) return OGRERR_FAILURE; FlushDeferedInsert(); if( iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() || GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone ) { if( iGeomField != 0 ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry field index : %d", iGeomField); } return OGRERR_FAILURE; } OGRGeomFieldDefn* poGeomFieldDefn = poFeatureDefn->GetGeomFieldDefn(iGeomField); /* Do not take the spatial filter into account */ osSQL.Printf( "SELECT ST_Extent(%s) FROM %s", OGRCARTODBEscapeIdentifier(poGeomFieldDefn->GetNameRef()).c_str(), OGRCARTODBEscapeIdentifier(osName).c_str()); json_object* poObj = poDS->RunSQL(osSQL); json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); if( poRowObj != NULL ) { json_object* poExtent = json_object_object_get(poRowObj, "st_extent"); if( poExtent != NULL && json_object_get_type(poExtent) == json_type_string ) { const char* pszBox = json_object_get_string(poExtent); const char * ptr, *ptrEndParenthesis; char szVals[64*6+6]; ptr = strchr(pszBox, '('); if (ptr) ptr ++; if (ptr == NULL || (ptrEndParenthesis = strchr(ptr, ')')) == NULL || ptrEndParenthesis - ptr > (int)(sizeof(szVals) - 1)) { CPLError( CE_Failure, CPLE_IllegalArg, "Bad extent representation: '%s'", pszBox); json_object_put(poObj); return OGRERR_FAILURE; } strncpy(szVals,ptr,ptrEndParenthesis - ptr); szVals[ptrEndParenthesis - ptr] = '\0'; char ** papszTokens = CSLTokenizeString2(szVals," ,",CSLT_HONOURSTRINGS); int nTokenCnt = 4; if ( CSLCount(papszTokens) != nTokenCnt ) { CPLError( CE_Failure, CPLE_IllegalArg, "Bad extent representation: '%s'", pszBox); CSLDestroy(papszTokens); json_object_put(poObj); return OGRERR_FAILURE; } // Take X,Y coords // For PostGis ver >= 1.0.0 -> Tokens: X1 Y1 X2 Y2 (nTokenCnt = 4) // For PostGIS ver < 1.0.0 -> Tokens: X1 Y1 Z1 X2 Y2 Z2 (nTokenCnt = 6) // => X2 index calculated as nTokenCnt/2 // Y2 index caluclated as nTokenCnt/2+1 psExtent->MinX = CPLAtof( papszTokens[0] ); psExtent->MinY = CPLAtof( papszTokens[1] ); psExtent->MaxX = CPLAtof( papszTokens[nTokenCnt/2] ); psExtent->MaxY = CPLAtof( papszTokens[nTokenCnt/2+1] ); CSLDestroy(papszTokens); json_object_put(poObj); return OGRERR_NONE; } } if( poObj != NULL ) json_object_put(poObj); if( iGeomField == 0 ) return OGRLayer::GetExtent( psExtent, bForce ); else return OGRLayer::GetExtent( iGeomField, psExtent, bForce ); }
int OGRCouchDBDataSource::Open( const char * pszFilename, int bUpdateIn) { int bHTTP = FALSE; if (strncmp(pszFilename, "http://", 7) == 0 || strncmp(pszFilename, "https://", 8) == 0) bHTTP = TRUE; else if (!EQUALN(pszFilename, "CouchDB:", 8)) return FALSE; bReadWrite = bUpdateIn; pszName = CPLStrdup( pszFilename ); if (bHTTP) osURL = pszFilename; else osURL = pszFilename + 8; if (osURL.size() > 0 && osURL[osURL.size() - 1] == '/') osURL.resize(osURL.size() - 1); const char* pszUserPwd = CPLGetConfigOption("COUCHDB_USERPWD", NULL); if (pszUserPwd) osUserPwd = pszUserPwd; if ((strstr(osURL, "/_design/") && strstr(osURL, "/_view/")) || strstr(osURL, "/_all_docs")) { return OpenView() != NULL; } /* If passed with http://useraccount.knownprovider.com/database, do not */ /* try to issue /all_dbs, but directly open the database */ const char* pszKnowProvider = strstr(osURL, ".iriscouch.com/"); if (pszKnowProvider != NULL && strchr(pszKnowProvider + strlen(".iriscouch.com/"), '/' ) == NULL) { return OpenDatabase() != NULL; } pszKnowProvider = strstr(osURL, ".cloudant.com/"); if (pszKnowProvider != NULL && strchr(pszKnowProvider + strlen(".cloudant.com/"), '/' ) == NULL) { return OpenDatabase() != NULL; } /* Get list of tables */ json_object* poAnswerObj = GET("/_all_dbs"); if (poAnswerObj == NULL) { if (!EQUALN(pszFilename, "CouchDB:", 8)) CPLErrorReset(); return FALSE; } if ( !json_object_is_type(poAnswerObj, json_type_array) ) { if ( json_object_is_type(poAnswerObj, json_type_object) ) { json_object* poError = json_object_object_get(poAnswerObj, "error"); json_object* poReason = json_object_object_get(poAnswerObj, "reason"); const char* pszError = json_object_get_string(poError); const char* pszReason = json_object_get_string(poReason); if (pszError && pszReason && strcmp(pszError, "not_found") == 0 && strcmp(pszReason, "missing") == 0) { json_object_put(poAnswerObj); poAnswerObj = NULL; CPLErrorReset(); return OpenDatabase() != NULL; } } if (poAnswerObj) { IsError(poAnswerObj, "Database listing failed"); json_object_put(poAnswerObj); return FALSE; } } int nTables = json_object_array_length(poAnswerObj); for(int i=0;i<nTables;i++) { json_object* poAnswerObjDBName = json_object_array_get_idx(poAnswerObj, i); if ( json_object_is_type(poAnswerObjDBName, json_type_string) ) { const char* pszDBName = json_object_get_string(poAnswerObjDBName); if ( strcmp(pszDBName, "_users") != 0 && strcmp(pszDBName, "_replicator") != 0 ) { papoLayers = (OGRLayer**) CPLRealloc(papoLayers, (nLayers + 1) * sizeof(OGRLayer*)); papoLayers[nLayers ++] = new OGRCouchDBTableLayer(this, pszDBName); } } } json_object_put(poAnswerObj); return TRUE; }
OGRErr OGRCARTODBTableLayer::ISetFeature( OGRFeature *poFeature ) { int i; if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) return OGRERR_FAILURE; FlushDeferedInsert(); GetLayerDefn(); if (!poDS->IsReadWrite()) { CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode"); return OGRERR_FAILURE; } if (poFeature->GetFID() == OGRNullFID) { CPLError( CE_Failure, CPLE_AppDefined, "FID required on features given to SetFeature()." ); return OGRERR_FAILURE; } CPLString osSQL; osSQL.Printf("UPDATE %s SET ", OGRCARTODBEscapeIdentifier(osName).c_str()); int bMustComma = FALSE; for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef()); osSQL += " = "; if( !poFeature->IsFieldSet(i) ) { osSQL += "NULL"; } else { OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType(); if( eType == OFTString || eType == OFTDateTime || eType == OFTDate || eType == OFTTime ) { osSQL += "'"; osSQL += OGRCARTODBEscapeLiteral(poFeature->GetFieldAsString(i)); osSQL += "'"; } else if( (eType == OFTInteger || eType == OFTInteger64) && poFeatureDefn->GetFieldDefn(i)->GetSubType() == OFSTBoolean ) { osSQL += poFeature->GetFieldAsInteger(i) ? "'t'" : "'f'"; } else osSQL += poFeature->GetFieldAsString(i); } } for(i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef()); osSQL += " = "; OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i); if( poGeom == NULL ) { osSQL += "NULL"; } else { OGRCartoDBGeomFieldDefn* poGeomFieldDefn = (OGRCartoDBGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(i); int nSRID = poGeomFieldDefn->nSRID; if( nSRID == 0 ) nSRID = 4326; char* pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, FALSE); osSQL += "'"; osSQL += pszEWKB; osSQL += "'"; CPLFree(pszEWKB); } } osSQL += CPLSPrintf(" WHERE %s = " CPL_FRMT_GIB, OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), poFeature->GetFID()); OGRErr eRet = OGRERR_FAILURE; json_object* poObj = poDS->RunSQL(osSQL); if( poObj != NULL ) { json_object* poTotalRows = json_object_object_get(poObj, "total_rows"); if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int ) { int nTotalRows = json_object_get_int(poTotalRows); if( nTotalRows > 0 ) { eRet = OGRERR_NONE; } else eRet = OGRERR_NON_EXISTING_FEATURE; } json_object_put(poObj); } return eRet; }
static int st_http_get_sync_info(u1db_sync_target *st, const char *source_replica_uid, const char **st_replica_uid, int *st_gen, int *source_gen, char **trans_id) { struct _http_state *state; struct _http_request req = {0}; char *url = NULL; const char *tmp = NULL; int status; long http_code; struct curl_slist *headers = NULL; json_object *json = NULL, *obj = NULL; if (st == NULL || source_replica_uid == NULL || st_replica_uid == NULL || st_gen == NULL || source_gen == NULL || st->implementation == NULL) { return U1DB_INVALID_PARAMETER; } status = impl_as_http_state(st->implementation, &state); if (status != U1DB_OK) { return status; } headers = curl_slist_append(NULL, "Content-Type: application/json"); if (headers == NULL) { status = U1DB_NOMEM; goto finish; } req.state = state; status = u1db__format_sync_url(st, source_replica_uid, &url); if (status != U1DB_OK) { goto finish; } status = curl_easy_setopt(state->curl, CURLOPT_HTTPGET, 1L); if (status != CURLE_OK) { goto finish; } // status = curl_easy_setopt(state->curl, CURLOPT_USERAGENT, "..."); status = curl_easy_setopt(state->curl, CURLOPT_URL, url); if (status != CURLE_OK) { goto finish; } req.body_buffer = req.header_buffer = NULL; status = simple_set_curl_data(state->curl, &req, &req, NULL); if (status != CURLE_OK) { goto finish; } status = maybe_sign_url(st, "GET", url, &headers); if (status != U1DB_OK) { goto finish; } status = curl_easy_setopt(state->curl, CURLOPT_HTTPHEADER, headers); if (status != CURLE_OK) { goto finish; } // Now do the GET status = curl_easy_perform(state->curl); if (status != CURLE_OK) { goto finish; } status = curl_easy_getinfo(state->curl, CURLINFO_RESPONSE_CODE, &http_code); if (status != CURLE_OK) { goto finish; } if (http_code != 200) { // 201 for created? shouldn't happen on GET status = http_code; goto finish; } if (req.body_buffer == NULL) { status = U1DB_INVALID_HTTP_RESPONSE; goto finish; } json = json_tokener_parse(req.body_buffer); if (json == NULL) { status = U1DB_NOMEM; goto finish; } obj = json_object_object_get(json, "target_replica_uid"); if (obj == NULL) { status = U1DB_INVALID_HTTP_RESPONSE; goto finish; } if (state->replica_uid == NULL) { // we cache this on the state object, because the api for get_sync_info // asserts that callers do not have to free the returned string. // This isn't a functional problem, because if the sync target ever // changed its replica uid we'd be seriously broken anyway. state->replica_uid = strdup(json_object_get_string(obj)); } else { if (strcmp(state->replica_uid, json_object_get_string(obj)) != 0) { // Our http target changed replica_uid, this would be a really // strange bug status = U1DB_INVALID_HTTP_RESPONSE; goto finish; } } *st_replica_uid = state->replica_uid; if (*st_replica_uid == NULL) { status = U1DB_NOMEM; goto finish; } obj = json_object_object_get(json, "target_replica_generation"); if (obj == NULL) { status = U1DB_INVALID_HTTP_RESPONSE; goto finish; } *st_gen = json_object_get_int(obj); obj = json_object_object_get(json, "source_replica_generation"); if (obj == NULL) { status = U1DB_INVALID_HTTP_RESPONSE; goto finish; } *source_gen = json_object_get_int(obj); obj = json_object_object_get(json, "source_transaction_id"); if (obj == NULL) { *trans_id = NULL; } else { tmp = json_object_get_string(obj); if (tmp == NULL) { *trans_id = NULL; } else { *trans_id = strdup(tmp); if (*trans_id == NULL) { status = U1DB_NOMEM; } } } finish: if (req.header_buffer != NULL) { free(req.header_buffer); } if (req.body_buffer != NULL) { free(req.body_buffer); } if (json != NULL) { json_object_put(json); } if (url != NULL) { free(url); } curl_slist_free_all(headers); return status; }