예제 #1
0
StringBuffer MHSyncItemInfo::formatExportedServices()
{
    StringBuffer formattedExportedServices("");
    KeyValuePair kvp = exportedServices.front();
    
    while (kvp.null() == false) {
        StringBuffer serviceName = kvp.getKey();
        StringBuffer serviceExportTime = kvp.getValue();
    
        if (serviceName.empty() == false) {
            StringBuffer formattedService;
            
            formattedService.sprintf("%s:%s", serviceName.c_str(),
                serviceExportTime.c_str());
            
            if (formattedExportedServices.empty() == false) { 
                formattedExportedServices.append(",");
            }
            
            formattedExportedServices.append(formattedService.c_str());
        }
        
        kvp = exportedServices.next();
    }
    
    return formattedExportedServices;
}
예제 #2
0
파일: build.cpp 프로젝트: raynorpat/cake
void build_run(const char* name, CommandListener& listener)
{
  for(Tools::iterator i = g_build_tools.begin(); i != g_build_tools.end(); ++i)
  {
    StringBuffer output;
    (*i).second.evaluate(output);
    build_set_variable((*i).first.c_str(), output.c_str());
  }

  {
    Project::iterator i = Project_find(g_build_project, name);
    if(i != g_build_project.end())
    {
      Build& build = (*i).second;
      for(Build::iterator j = build.begin(); j != build.end(); ++j)
      {
        StringBuffer output;
        (*j).evaluate(output);
        listener.execute(output.c_str());
      }
    }
    else
    {
      globalErrorStream() << "build " << makeQuoted(name) << " not defined";
    }
  }
}
예제 #3
0
void MHSyncItemInfo::setExportedServicesFromString(const char* servicesList)
{
    StringBuffer services(servicesList);
    
    if (services.empty() == false) {
        ArrayList servicesParam;
        int servicesNum = 0;
        
        services.split(servicesParam, ",");
        
        servicesNum = servicesParam.size();
        
        for (int i = 0; i < servicesNum; i++) {
            StringBuffer* serviceParamStr = static_cast<StringBuffer *>(servicesParam.get(i));
                
            if ((serviceParamStr) && (serviceParamStr->empty() == false)) {
                ArrayList serviceParam;
                              
                serviceParamStr->split(serviceParam, ":");
                
                if (serviceParam.size() == 2) {
                    StringBuffer* serviceName = static_cast<StringBuffer *>(serviceParam.get(0));
                    StringBuffer* serviceExportTime = static_cast<StringBuffer *>(serviceParam.get(1));
                        
                    exportedServices.put(serviceName->c_str(), serviceExportTime->c_str());
                }
            }
        }
    }
}
예제 #4
0
void leadHQHandle(void) {
  int rsize;
  unsigned short index[32]; // <10 keypairs in the incoming json

  // only continue if new data to read
  if (!Scout.wifi.client.available()) {
    return;
  }

  // Read a block of data and look for packets
  while ((rsize = hqIncoming.readClient(Scout.wifi.client, 128))) {
    int nl;
    while((nl = hqIncoming.indexOf('\n')) >= 0) {
     // look for a packet
      if (hqVerboseOutput) {
        Serial.print(F("looking for packet in: "));
        Serial.println(hqIncoming);
      }

      // Parse JSON up to the first newline
      if (!js0n((const unsigned char*)hqIncoming.c_str(), nl, index, 32)) {
        leadIncoming(hqIncoming.c_str(), nl, index);
      } else {
        if (hqVerboseOutput) {
          Serial.println(F("JSON parse failed"));
        }
      }

      // Remove up to and including the newline
      hqIncoming.remove(0, nl + 1);
    }
  }
}
예제 #5
0
파일: Log.cpp 프로젝트: ruphy/kfunambol
winLog::winLog(bool resetLog, const char* path, const char* name) {

    setLogPath(path);
    setLogName(name);

    // MUST use a wchar_t* logDir to manage correctly international chars.
    // If using char* logDir and UTF-8, fopen() is not working correctly and
    // will fail to open the log file. (with UTF-8... why?)
    // So we use _wfopen() and a wchar_t* logDir.
    StringBuffer logDir;
    logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
    WCHAR* tmp = toWideChar(logDir.c_str());
    wlogDir = tmp;
    delete [] tmp;

    //
    // Test to ensure the log file is writable (only if path is set)
    //
    if (path) {
        logFile = _wfopen(wlogDir.c_str(), TEXT("a+"));
        if (logFile == NULL) {
            WCHAR tmp[512];
            wsprintf(tmp, TEXT("Unable to write log file: \"%s\".\nPlease check your user's permissions."), wlogDir.c_str());
            MessageBox(NULL, tmp, TEXT("Funambol"), MB_SETFOREGROUND | MB_OK);
        }
        else {
            fclose(logFile);

            if (resetLog) {
                reset(FUNAMBOL_HEADER);
            }
        }
    }
}
END_TEST

/**
* Removed the STATUS from the winevent parser
*/
BEGIN_TEST(WinEventNoSTATUS)
{
    int ret = 0;
    SyncItem* item = NULL;
    WCHAR* internalKey = NULL;
    wstring propValue; 

    WindowsSyncSource* ss = createAppointmentWindowsSyncSource();   
    WIN_ASSERT_NOT_NULL(ss, TEXT("The syncSource is null."));

    StringBuffer VCal;
    VCal.append("BEGIN:VCALENDAR\r\n");
    VCal.append("VERSION:1.0\r\n");
    VCal.append("BEGIN:VEVENT\r\n");
    VCal.append("X-FUNAMBOL-FOLDER:DEFAULT_FOLDER\r\n");
    VCal.append("X-FUNAMBOL-ALLDAY:1\r\n");
    VCal.append("DTSTART:20110407\r\n");
    VCal.append("DTEND:20110408\r\n");
    VCal.append("X-MICROSOFT-CDO-BUSYSTATUS:FREE\r\n");
    VCal.append("CATEGORIES:\r\n");
    VCal.append("DESCRIPTION:\r\n");
    VCal.append("LOCATION:Roma\r\n");
    VCal.append("PRIORITY:1\r\n");
    VCal.append("STATUS:NEED ACTION\r\n");
    VCal.append("X-MICROSOFT-CDO-REPLYTIME:\r\n");
    VCal.append("SUMMARY;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:Da test\r\n");
    VCal.append("CLASS:PUBLIC\r\n");
    VCal.append("AALARM:20110406T060000Z;;0;\r\n");
    VCal.append("RRULE:\r\n");
    VCal.append("X-FUNAMBOL-BILLINGINFO:\r\n");
    VCal.append("X-FUNAMBOL-COMPANIES:\r\n");
    VCal.append("X-FUNAMBOL-MILEAGE:\r\n");
    VCal.append("X-FUNAMBOL-NOAGING:0 \r\n");
    VCal.append("END:VEVENT\r\n");
    VCal.append("END:VCALENDAR");

    item = new SyncItem(TEXT("GUID"));
    item->setData(VCal.c_str(), VCal.length());
    
    WCHAR* tt = toWideChar(VCal.c_str());

    WinEvent d(tt);
    printf("%S", d.toString().c_str());        

    // insert test item
    ret = ss->addItem(*item);
    WIN_ASSERT_EQUAL(ret, 201, TEXT("Adding item is not correct"));    
    internalKey = (WCHAR*)item->getKey();        
    
    delete item;
    delete ss;
}
예제 #7
0
void
SchemaTypeTuple::checkRule(
	const SchemaValidator *		sv,
	const Configuration *		cfg,
	const char *				typeName,
	const StringVector &		typeArgs,
	const char *				rule) const throw(ConfigurationException)
{
    (void) cfg;
    
	StringBuffer				msg;
	int							i;
	int							len;
	const char *				elemType;
	SchemaType *				typeDef;

	//--------
	// Check there is at least one pair of type and name arguments.
	//--------
	len = typeArgs.length();
	if ((len == 0) || (len % 2 != 0)) {
		msg << "the '" << typeName << "' type requires pairs of type and "
			<< "name arguments in rule '" << rule << "'";
		throw ConfigurationException(msg.c_str());
	}

	//--------
	// Check that all the type arguments are valid types.
	//--------
	for (i = 0; i < len; i+=2) {
		elemType = typeArgs[i+0];
		typeDef = findType(sv, elemType);
		if (typeDef == 0) {
			msg << "unknown type '" << elemType << "' in rule '" << rule << "'";
			throw ConfigurationException(msg.c_str());
		}
		switch (typeDef->cfgType()) {
		case Configuration::CFG_STRING:
			break;
		case Configuration::CFG_LIST:
			msg << "you cannot embed a list type ('" << elemType
				<< "') inside a " << "tuple in rule '" << rule << "'";
			throw ConfigurationException(msg.c_str());
		case Configuration::CFG_SCOPE:
			msg << "you cannot embed a scope type ('" << elemType
				<< "') inside a " << "tuple in rule '" << rule << "'";
			throw ConfigurationException(msg.c_str());
		default:
			assert(0); // Bug!
		}
	}
}
예제 #8
0
void HttpConnection::readResponseHeaders() 
{
    WCHAR *wbuffer = new WCHAR[1024];
    DWORD  ddsize = 1024;
	StringBuffer headerString;

    responseHeaders.clear();

    BOOL reqDone = HttpQueryInfo(req, HTTP_QUERY_RAW_HEADERS_CRLF ,(LPVOID)wbuffer, &ddsize, NULL);
    if (reqDone == false) {
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
            // Allocate the necessary buffer.
            delete [] wbuffer;
            wbuffer = new WCHAR[ddsize];
            reqDone = HttpQueryInfo(req, HTTP_QUERY_RAW_HEADERS_CRLF ,(LPVOID)wbuffer, &ddsize, NULL);
        }
    }
    if (reqDone) {
		headerString.convert(wbuffer);
		LOG.debug("Response Headers:", headerString.c_str());

		ArrayList headers;
		headerString.split(headers, "\r\n");

		StringBuffer *prop;

		for(ArrayElement* e=headers.front(); e; e=headers.next()) {
			prop = dynamic_cast<StringBuffer *>(e);
			if(prop->empty()) continue;

			size_t colon = prop->find(":");
			if (colon != StringBuffer::npos) {
				StringBuffer key = prop->substr(0, colon);
				StringBuffer value = prop->substr(colon+1);
				responseHeaders.put(key.trim(),value.trim());                              
                if (canBeLogged(key)) {
				    LOG.debug("\t%s : %s", key.c_str(), value.c_str());
                } else {
                    LOG.debug("\t%s : *****", key.c_str());
                }
			}
			else {
				LOG.debug("\t%s", prop->c_str());
			}
		}
    } else {
        DWORD err = GetLastError();
        const char* msg = createHttpErrorMessage(err);
        LOG.error("[HttpConnection] Error reading response headers - code %d: %s", err, msg);
        delete [] msg;
    }
}
예제 #9
0
파일: LexBase.cpp 프로젝트: offa/config4cpp
LexBase::LexBase(
	Configuration::SourceType	sourceType,
	const char *				source,
	UidIdentifierProcessor *	uidIdentifierProcessor)
												throw(ConfigurationException)
{
	StringBuffer				msg;

	//--------
	// Initialize state for the multi-byte functions in the C library.
	//--------
	memset(&m_mbtowcState, 0, sizeof(mbstate_t));

	m_keywordInfoArray     = 0;
	m_keywordInfoArraySize = 0;
	m_funcInfoArray        = 0;
	m_funcInfoArraySize    = 0;

	m_uidIdentifierProcessor = uidIdentifierProcessor;
	m_amOwnerOfUidIdentifierProcessor = false;
	m_sourceType = sourceType;
	m_source = source;
	m_lineNum = 1;
	m_ptr = 0;
	m_atEOF = false;
	switch (sourceType) {
	case Configuration::INPUT_FILE:
		if (!m_file.open(source)) {
			msg << "cannot open " << source << ": " << strerror(errno);
			throw ConfigurationException(msg.c_str());
		}
		break;
	case Configuration::INPUT_STRING:
		m_ptr = m_source;
		break;
	case Configuration::INPUT_EXEC:
		if (!execCmd(source, m_execOutput)) {
			msg << "cannot parse 'exec#" << source << "': "
				<< m_execOutput.c_str();
			throw ConfigurationException(msg.c_str());
		}
		m_ptr = m_execOutput.c_str();
		break;
	default:
		assert(0); // Bug!
		break;
	}

	nextChar(); // initialize m_ch
}
예제 #10
0
파일: Log.cpp 프로젝트: ruphy/kfunambol
void winLog::setLogPath(const char* configLogPath) {

    if (configLogPath != NULL) {
        logPath = configLogPath;
    } else {
        logPath = ".";
    }
    if (logName.length() > 0){
        StringBuffer logDir;
        logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
        WCHAR* tmp = toWideChar(logDir.c_str());
        wlogDir = tmp;
        delete [] tmp;
    }
}
예제 #11
0
void leadHQHandle(void) {
  int rsize = 0;
  int nl;
  unsigned short index[32]; // <10 keypairs in the incoming json

  if(Scout.handler.isBridged)
  {
    rsize = (int)Scout.handler.bridge.length();
    hqIncoming += Scout.handler.bridge;
    Scout.handler.bridge = "";
  } else if (WifiModule::instance.bp()) {
    if (WifiModule::instance.bp()->client.available()) {
      rsize = hqIncoming.readClient(WifiModule::instance.bp()->client, 128);
      if(rsize > 0) Scout.handler.seen = SleepHandler::uptime().seconds;
    }
  }

  // only continue if new data to process
  if(rsize <= 0) return;
  
  // Read a block of data and look for packets
  while((nl = hqIncoming.indexOf('\n')) >= 0) {
    // look for a packet
    if(nl)
    {
      if (Scout.handler.isVerbose) {
        Serial.print(F("looking for packet in: "));
        Serial.println(hqIncoming);
      }

      // Parse JSON up to the first newline
      if (!js0n((const unsigned char*)hqIncoming.c_str(), nl, index, 32)) {
        leadIncoming(hqIncoming.c_str(), nl, index);
      } else {
        if (Scout.handler.isVerbose) {
          Serial.println(F("JSON parse failed"));
        }
      }
    }else{
      if (Scout.handler.isVerbose) {
        Serial.println(F("HQ ack'd"));
      }
    }

    // Remove up to and including the newline
    hqIncoming.remove(0, nl + 1);
  }
}
예제 #12
0
    void testConvert() {

        StringBuffer str(TEST_STRING);

        char* toUtf8   = toMultibyte(TEXT(TEST_STRING));
        char* toLatin1 = toMultibyte(TEXT(TEST_STRING), "iso_8859-1");

        StringBuffer cnv;
        cnv.convert(TEXT(TEST_STRING));
        fprintf(stderr, "\nConverted string: %s\n", cnv.c_str());
        CPPUNIT_ASSERT((strcmp(cnv.c_str(), toUtf8) == 0));

        cnv.convert(TEXT(TEST_STRING), "iso_8859-1");
        fprintf(stderr, "\nConverted string: %s\n", cnv.c_str());
        CPPUNIT_ASSERT((strcmp(cnv.c_str(), toLatin1) == 0));
    }
예제 #13
0
파일: build.cpp 프로젝트: raynorpat/cake
 void evaluate(StringBuffer& output)
 {
   StringBuffer variable;
   bool in_variable = false;
   for(const char* i = m_string.c_str(); *i != '\0'; ++i)
   {
     if(!in_variable)
     {
       switch(*i)
       {
       case '[':
         in_variable = true;
         break;
       default:
         output.push_back(*i);
         break;
       }
     }
     else
     {
       switch(*i)
       {
       case ']':
         in_variable = false;
         output.push_string(build_get_variable(variable.c_str()));
         variable.clear();
         break;
       default:
         variable.push_back(*i);
         break;
       }
     }
   }
 }
예제 #14
0
      void spit (string const& filename, StringBuffer const& content) {
        int fd = TRI_CREATE(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP);

        if (fd == -1) {
          LOG_TRACE("open failed for '%s' with %s", filename.c_str(), strerror(errno));
          THROW_FILE_OPEN_ERROR("open", filename, "O_WRONLY | O_CREAT | O_TRUNC", errno);
        }

        char const* ptr = content.c_str();
        size_t len = content.length();

        while (0 < len) {
          ssize_t n = TRI_WRITE(fd, ptr, len);

          if (n < 1) {
            TRI_CLOSE(fd);
            LOG_TRACE("write failed for '%s' with %s and result %d on %d",
                      filename.c_str(),
                      strerror(errno),
                      (int) n,
                      fd); 
            THROW_FILE_FUNC_ERROR("write", "", errno);
          }

          ptr += n;
          len -= n;
        }

        TRI_CLOSE(fd);
        return;
      }
// called to send the first/next chunk of a command to another scout
static void leadCommandChunk() {
  int len = leadCommandChunks.length() - leadCommandChunksAt;
  if (len > 100) {
    len = 100;
  } else {
    len++; // null terminator at end
  }

  leadCommandReq.dstAddr = leadCommandTo;
  leadCommandReq.dstEndpoint = 2;
  leadCommandReq.srcEndpoint = 3;
  leadCommandReq.options = NWK_OPT_ENABLE_SECURITY;
  leadCommandReq.data = (uint8_t*)leadCommandChunks.c_str() + leadCommandChunksAt;
  leadCommandReq.size = len;
  leadCommandReq.confirm = leadCommandChunkConfirm;
  NWK_DataReq(&leadCommandReq);
  //RgbLed.blinkCyan(200);

  if (hqVerboseOutput) {
    Serial.print(leadCommandTo);
    Serial.print(F(" len "));
    Serial.print(len);
    Serial.println(F("->chunk"));
  }
}
예제 #16
0
void HttpUploader::setRequestHeaders(const StringBuffer& luid, HttpConnection& httpConnection, InputStream& inputStream) {
    
    StringBuffer dataSize;
    int totalSize = inputStream.getTotalSize();
    LOG.debug("[%s]: input stream size is %i", __FUNCTION__, totalSize);
    LOG.debug("[%s]: totalDataToUpload size is %i", __FUNCTION__, totalDataToUpload);
    if (totalDataToUpload > 0) {
        totalSize = totalDataToUpload;
    } 
    dataSize.sprintf("%d", totalSize);
    

    httpConnection.setRequestHeader(HTTP_HEADER_ACCEPT,         "*/*");
    httpConnection.setRequestHeader(HTTP_HEADER_CONTENT_TYPE,   "application/octet-stream");

    // set transfer enconding to chunked
    //httpConnection.setRequestHeader(HTTP_HEADER_TRANSFER_ENCODING, "chunked");

    // set Funambol mandatory custom headers
    httpConnection.setRequestHeader(HTTP_HEADER_X_FUNAMBOL_FILE_SIZE, dataSize);
    httpConnection.setRequestHeader(HTTP_HEADER_X_FUNAMBOL_DEVICE_ID, deviceID);
    httpConnection.setRequestHeader(HTTP_HEADER_X_FUNAMBOL_LUID, luid);
    
    if (partialUploadedData > 0) {
        StringBuffer s;
        s.sprintf("bytes %d-%d/%d", partialUploadedData, totalSize-1, totalSize);
        
        httpConnection.setRequestHeader(HTTP_HEADER_CONTENT_RANGE, s.c_str());
    }
}
BufferInputStream::BufferInputStream(const StringBuffer& dataString) : InputStream() {

    this->data      = dataString.c_str();
    this->totalSize = dataString.length();
    this->position  = 0;
    this->eofbit    = 0;
}
예제 #18
0
StringBuffer MHLabelsStore::formatUpdateItemStmt(MHStoreEntry* entry)
{
    StringBuffer stmt("");
    
    if (entry == NULL) {
        LOG.error("%s: invalid argument", __FUNCTION__);
        return stmt;
    }
    
    MHLabelInfo* itemInfo = dynamic_cast<MHLabelInfo*>(entry);
    if (itemInfo == NULL) {
        LOG.error("%s: invalid parameter", __FUNCTION__);
        return stmt;
    }
    
    unsigned long itemId = itemInfo->getLuid();
    const char* n = itemInfo->getName().c_str();
    StringBuffer name = n != NULL ? n : "";
    
    uint32_t guid = itemInfo->getGuid();
    char* queryBuilt = sqlite3_mprintf(updateQuery.c_str(), name.c_str(), guid, itemId);
    stmt.sprintf("%s", queryBuilt); 
    sqlite3_free(queryBuilt);

    return stmt;
}
예제 #19
0
	String CallFlashFunc(const String& argtype,
									const String& func,
									const String& arg)
	{
		if(!m_pFlash) return "";

		String args;
		StringBuffer<wchar_t> request;

		if ( !argtype.empty() )
		{
			args = String::Format("<%s>%s</%s>", argtype, arg, argtype);
		}

		// take care with XML formatting: there should be no spaces in it or the
		// call would fail!
		request = String::Format
							(
								"<invoke name=\"%s\" returntype=\"xml\">"
									"<arguments>"
									"%s"
									"</arguments>"
								"</invoke>",
								func,
								args
							);

		const wchar_t* v=m_pFlash->CallFunction(request.c_str());
		return v;
	}
예제 #20
0
파일: Log.cpp 프로젝트: ruphy/kfunambol
void winLog::setLogName(const char* configLogName) {

    if (configLogName != NULL) {
        logName = configLogName;
    }
    else {
        logName = LOG_NAME;
    }
    if (logPath){
        StringBuffer logDir;
        logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
        WCHAR* tmp = toWideChar(logDir.c_str());
        wlogDir = tmp;
        delete [] tmp;
    }
}
예제 #21
0
/**
* The way to calculate the cache is the follow:
* loop on the current element against an array list
* that has the cache. It is the copy of the original cache.
* When an current element is found in the cache, it is removed
* from the cache copy. At the end the remained element
* in the cache are the deleted ones.
*/
bool CacheSyncSource::fillItemModifications() {
    
    // all the current items keys list
    Enumeration* items = (Enumeration*)getAllItemList();

    if (!items) {
        LOG.error("Error in fillItemModification");
        return false;
    }

    // all the action are done on the copy so we can delete
    // the element found. The remained are the deleted by the user.        
    Enumeration& e = cache->getProperties();
    ArrayList cacheCopy;
    while(e.hasMoreElement()) {
        cacheCopy.add(*e.getNextElement());
    }        
    //if (e) {
    //    delete e;
    //}

    StringBuffer* key;
    KeyValuePair* kvp;

    ArrayListEnumeration *newitems = new ArrayListEnumeration(),
                         *moditems = new ArrayListEnumeration();

    if (items) {
        while(items->hasMoreElement()) {
            key = (StringBuffer*)items->getNextElement();
            int size = cacheCopy.size();
            bool foundnew = true;

            for (int i = 0; i < size; i++) {
                kvp = (KeyValuePair*)(cacheCopy[i]);
                if (strcmp(kvp->getKey(), key->c_str()) == 0) {
                    foundnew = false;
                    // see if it is updated.
                    StringBuffer sign = getItemSignature(*key);
                    if (sign != kvp->getValue()) {
                        // there is an update. if equal nothing to do...
                        moditems->add(*key);                      
                    }
                    cacheCopy.removeElementAt(i);
                    break;
                }
            }
            if (foundnew) {
                newitems->add(*key);
            }
        }
    }
        
    newKeys = newitems;
    updatedKeys = moditems;           
    deletedKeys = new ArrayListEnumeration(cacheCopy);    
    
    delete items; 
    return true;
}
    /// Loads data for testing the 'testFileName' file.
    void loadTestFileData(const char* testFileName) {

        fileName = getTestFileFullPath(SAMPLE_FILES_DIR, testFileName);
        const char* fileContent = loadTestFile(SAMPLE_FILES_DIR, testFileName, true);  // must be binary mode!
        int fileSize = (int)fgetsize(fileName.c_str());

        const WCHAR* wtestFileName = toWideChar(testFileName);
        
        FileData fileData;
        fileData.setName(wtestFileName);
        fileData.setSize(fileSize);
        fileData.setBody(fileContent, fileSize);

        unsigned long tstamp = getFileModTime(fileName);
        StringBuffer modTime = unixTimeToString(tstamp, true);  // file's mod time is already in UTC
        WString wmodTime;
        wmodTime = modTime;
        fileData.setModified(wmodTime);

        fileDataContent = fileData.format();
        fileDataSize = (int)strlen(fileDataContent);

        delete [] wtestFileName;
        delete [] fileContent;
    }
void UpdateManager::setURLCheck(const StringBuffer& syncURL)
{
    // Get the host & port info
    URL url;
    url.setURL(syncURL.c_str());
    StringBuffer port(":80");
    if (url.port != 0) { 
        port = ":"; 
        port += itow(url.port); 
    }        
            
    // Compose the url
    StringBuffer urlCheck(url.protocol);
    urlCheck += "://"; 
    urlCheck += url.host;
    urlCheck += port;
    urlCheck += UP_URL_RESOURCE;
    
    StringBuffer ss(UP_URL_RESOURCE);
    if (ss.find("http://")  != StringBuffer::npos ||
        ss.find("https://") != StringBuffer::npos ) {
        urlCheck = UP_URL_RESOURCE;
    }

    LOG.debug("Url to check = %s", urlCheck.c_str());
    
    // Save to registry.
    UpdaterConfig& config = ((OutlookConfig*)getConfig())->getUpdaterConfig();
    config.setUrlCheck(urlCheck);
    config.save();
}
예제 #24
0
bool FSyncOpt::parseCmdline(int args_num, char** args_val) 
{
    if (parser.parse(args_num, const_cast<const char **>(args_val), opts, args) == false) {
        return false;
    }

    if (optionSet("verbose")) {
        verbose = VERBOSE;
    } else if (optionSet("quiet")) {
        verbose = QUIET;
    }
    FSyncConfig *config = FSyncConfig::getInstance();

    // Get log options
    StringBuffer logLevelName = opts["loglevel"];
    if (!logLevelName.null()) {
        LogLevel logLevel;
        if (logLevelName == "error") {
            logLevel = LOG_LEVEL_NONE;
        } else if (logLevelName == "info") {
            logLevel = LOG_LEVEL_INFO;	
        } else if (logLevelName == "debug") {
            logLevel = LOG_LEVEL_DEBUG;
        } else {
            fprintf(stderr, "%s: unrecognized log level: '%s'\n",
                parser.getProgramName().c_str(), logLevelName.c_str());

            exit(EXIT_FAILURE);
        }
        config->getDeviceConfig().setLogLevel(logLevel);
        LOG.setLevel(config->getDeviceConfig().getLogLevel());
    }

    // Get server option
    StringBuffer serverUrl = opts["server"];
    if (!serverUrl.null()) {
        config->getAccessConfig().setSyncURL(serverUrl);
    }

    // Get local dir
    StringBuffer dir = opts["dir"];
    if (!dir.null()) {
        config->setSyncPath(dir);
        // TODO: reset anchors if different.
    }

    // Get username
    StringBuffer user = opts["user"];
    if (!user.null()) {
        config->getAccessConfig().setUsername(user);
    }

    // Get password (not secure, it's an example!) 
    StringBuffer pass = opts["password"];
    if (!pass.null()) {
        config->getAccessConfig().setPassword(pass);
    }

    return true;
}
예제 #25
0
static char *
escapeString(const char * str)
{
	int					i;
	int					len;
	StringBuffer		buf;
	char *				result;

	len = strlen(str);
	for (i = 0; i < len; i++) {
		switch (str[i]) {
		case '\t':
			buf.append("%t");
			break;
		case '\n':
			buf.append("%n");
			break;
		case '%':
			buf.append("%%");
			break;
		case '"':
			buf.append("%\"");
			break;
		default:
			buf.append(str[i]);
			break;
		}
	}
	result = new char[buf.length() + 1];
	strcpy(result, buf.c_str());
	return result;
}
예제 #26
0
static string rule2string(CPDatabase db, CPCube cube, Node* node)
{
	StringBuffer sb;
	node->appendRepresentation(&sb, db, cube);

	return sb.c_str();
}
예제 #27
0
SyncItem* LOSyncSource::getNextNewItem() {
    
    if (getUseAdd() == false) {
        return NULL;
    }
    if (count == 2) {
        return NULL;
    }
    
    StringBuffer name = getSyncItemName();
    WCHAR key[256];
    wsprintf(key, TEXT(WCHAR_PRINTF_STRING), name.c_str());
    wcscat(key, getName());    

    SyncItem* item = new SyncItem(key);    
    if (getUseDataEncoding()) {
        // just to test that the api works properly with custom encoding
        item->setDataEncoding("bin");
    }


    char* data = getNewCard(true);
    item->setData(data, (long)strlen(data));
    
    delete [] data;
    return item;

}
예제 #28
0
파일: build.cpp 프로젝트: raynorpat/cake
 void flush()
 {
   if(!m_buffer.empty())
   {
     m_tool.push_back(new VariableString(m_buffer.c_str()));
     m_buffer.clear();
   }
 }
예제 #29
0
static bool fieldCommands(NWK_DataInd_t *ind) {
  int ret;
  if (hqVerboseOutput) {
    Serial.print(F("Received command"));
    Serial.print(F("lqi: "));
    Serial.print(ind->lqi);
    Serial.print(F("  "));
    Serial.print(F("rssi: "));
    Serial.println(ind->rssi);
  }

  if (fieldAnswerTo) {
    if (hqVerboseOutput) {
      Serial.println(F("can't receive command while sending answer"));
    }
    return false;
  }

  if (!fieldCommand.concat((const char*)ind->data, ind->size)) {
    return false; // TODO we need to restart or something, no memory
  }

  // when null terminated, do the message
  if (fieldCommand[fieldCommand.length() - 1] != '\0') {
    if (hqVerboseOutput) {
      Serial.println(F("waiting for more"));
    }
    return true;
  }

  if (hqVerboseOutput) {
    Serial.print(F("running command "));
    Serial.println(fieldCommand);
  }

  // run the command and chunk back the results
  setOutputHandler(&printToString<&fieldCommandOutput>);

  // TODO: Once bitlash fixes const-correctness, this and similar casts
  // should be removed.
  ret = (int)doCommand(const_cast<char *>(fieldCommand.c_str()));
  fieldCommand = (char*)NULL;

  resetOutputHandler();

  if (hqVerboseOutput) {
    Serial.print(F("got result "));
    Serial.println(ret);
  }

  // send data back in chunks
  fieldAnswerTo = ind->srcAddr;
  fieldAnswerChunksAt = 0;
  fieldAnswerRetries = 0;
  fieldAnswerChunk();

  return true;
}
예제 #30
0
파일: build.cpp 프로젝트: raynorpat/cake
 void evaluate(StringBuffer& output)
 {
   StringBuffer buffer;
   m_test->evaluate(buffer);
   if(!string_empty(buffer.c_str()))
   {
     m_result->evaluate(output);
   }
 }