コード例 #1
0
ファイル: RegExp.cpp プロジェクト: aeddi/gecko-dev
static bool
EscapeNakedForwardSlashes(StringBuffer &sb, const CharT *oldChars, size_t oldLen)
{
    for (const CharT *it = oldChars; it < oldChars + oldLen; ++it) {
        if (*it == '/' && (it == oldChars || it[-1] != '\\')) {
            /* There's a forward slash that needs escaping. */
            if (sb.empty()) {
                /* This is the first one we've seen, copy everything up to this point. */
                if (mozilla::IsSame<CharT, jschar>::value && !sb.ensureTwoByteChars())
                    return false;

                if (!sb.reserve(oldLen + 1))
                    return false;

                sb.infallibleAppend(oldChars, size_t(it - oldChars));
            }
            if (!sb.append('\\'))
                return false;
        }

        if (!sb.empty() && !sb.append(*it))
            return false;
    }

    return true;
}
コード例 #2
0
ファイル: StringBufferTest.cpp プロジェクト: ruphy/kfunambol
    //////////////////////////////////////////////////////// Test /////
    // Test null() and empty() behavior
    void testEmpty() {
        StringBuffer s;
        CPPUNIT_ASSERT(s.empty());
        CPPUNIT_ASSERT(s.null());

        s = "";

        CPPUNIT_ASSERT( s.empty() );
        CPPUNIT_ASSERT( !s.null() );

    }
コード例 #3
0
static bool
EscapeRegExpPattern(StringBuffer& sb, const CharT* oldChars, size_t oldLen)
{
    bool inBrackets = false;
    bool previousCharacterWasBackslash = false;

    for (const CharT* it = oldChars; it < oldChars + oldLen; ++it) {
        CharT ch = *it;
        if (!previousCharacterWasBackslash) {
            if (inBrackets) {
                if (ch == ']')
                    inBrackets = false;
            } else if (ch == '/') {
                // There's a forward slash that needs escaping.
                if (sb.empty()) {
                    // This is the first char we've seen that needs escaping,
                    // copy everything up to this point.
                    if (!SetupBuffer(sb, oldChars, oldLen, it))
                        return false;
                }
                if (!sb.append('\\'))
                    return false;
            } else if (ch == '[') {
                inBrackets = true;
            }
        }

        if (IsLineTerminator(ch)) {
            // There's LineTerminator that needs escaping.
            if (sb.empty()) {
                // This is the first char we've seen that needs escaping,
                // copy everything up to this point.
                if (!SetupBuffer(sb, oldChars, oldLen, it))
                    return false;
            }
            if (!previousCharacterWasBackslash) {
                if (!sb.append('\\'))
                    return false;
            }
            if (!AppendEscapedLineTerminator(sb, ch))
                return false;
        } else if (!sb.empty()) {
            if (!sb.append(ch))
                return false;
        }

        if (previousCharacterWasBackslash)
            previousCharacterWasBackslash = false;
        else if (ch == '\\')
            previousCharacterWasBackslash = true;
    }

    return true;
}
コード例 #4
0
ファイル: config2cpp-main.cpp プロジェクト: 2mia/config4cpp
void
calculateRuleForName(
	const Configuration *		cfg,
	const char *				name,
	const char *				uName,
	const StringVector &		wildcardedNamesAndTypes,
	StringBuffer &				rule)
{
	int							i;
	int							len;
	const char *				str;
	const char *				keyword;
	const char *				wildcardedName;
	const char *				type;

	rule.empty();
	len = wildcardedNamesAndTypes.length();
	for (i = 0; i < len; i+=3) {
		keyword        = wildcardedNamesAndTypes[i+0]; // @optional or @required
		wildcardedName = wildcardedNamesAndTypes[i+1];
		type           = wildcardedNamesAndTypes[i+2];
		if (Configuration::patternMatch(uName, wildcardedName)) {
			rule << keyword << " " << uName << " = " << type;
			return;
		}
	}

	//--------
	// We couldn's determine the type from the wildcarded_names_and_types 
	// table. So we fall back to using heuristics to guess a good type.
	//--------
	if (cfg->type("", name) == Configuration::CFG_SCOPE) {
		rule << uName << " = scope";
	} else if (cfg->type("", name) == Configuration::CFG_LIST) {
		rule << uName << " = list[string]";
	} else {
		str = cfg->lookupString("", name);
		if (cfg->isBoolean(str)) {
			rule << uName << " = boolean";
		} else if (cfg->isInt(str)) {
			rule << uName << " = int";
		} else if (cfg->isFloat(str)) {
			rule << uName << " = float";
		} else if (cfg->isDurationSeconds(str)) {
			rule << uName << " = durationSeconds";
		} else if (cfg->isDurationMilliseconds(str)) {
			rule << uName << " = durationMilliseconds";
		} else if (cfg->isDurationMicroseconds(str)) {
			rule << uName << " = durationMicroseconds";
		} else if (cfg->isMemorySizeBytes(str)) {
			rule << uName << " = memorySizeBytes";
		} else if (cfg->isMemorySizeKB(str)) {
			rule << uName << " = memorySizeKB";
		} else if (cfg->isMemorySizeMB(str)) {
			rule << uName << " = memorySizeMB";
		} else {
			rule << uName << " = string";
		}
	}
}
コード例 #5
0
ファイル: MHSyncItemInfo.cpp プロジェクト: fieldwind/syncsdk
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());
                }
            }
        }
    }
}
コード例 #6
0
ファイル: MHSyncItemInfo.cpp プロジェクト: fieldwind/syncsdk
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;
}
コード例 #7
0
    void testRemoveProperty() {
        // Write a value into the property file
        propFile->setPropertyValue("property4", "value4");
        propFile->setPropertyValue("  space  ", "  val space ");
        propFile->close();
        // Remove it
        int success = propFile->removeProperty("property4");
        CPPUNIT_ASSERT(success == 0);
        // Now read back
        StringBuffer value = propFile->readPropertyValue("property4");
        CPPUNIT_ASSERT(value.empty());
        
        StringBuffer valueS = propFile->readPropertyValue("space");
        CPPUNIT_ASSERT(value.empty());

    }
コード例 #8
0
ファイル: ext_url.cpp プロジェクト: kodypeterson/hiphop-php
static void url_encode_array(StringBuffer &ret, CVarRef varr,
                             std::set<void*> &seen_arrs,
                             CStrRef num_prefix, CStrRef key_prefix,
                             CStrRef key_suffix, CStrRef arg_sep) {
  void *id = varr.is(KindOfArray) ?
    (void*)varr.getArrayData() : (void*)varr.getObjectData();
  if (!seen_arrs.insert(id).second) {
    return; // recursive
  }

  Array arr = varr.toArray();

  for (ArrayIter iter(arr); iter; ++iter) {
    Variant data = iter.second();
    if (data.isNull() || data.isResource()) continue;

    String key = iter.first();
    bool numeric = key.isNumeric();

    if (data.is(KindOfArray) || data.is(KindOfObject)) {
      String encoded;
      if (numeric) {
        encoded = key;
      } else {
        encoded = StringUtil::UrlEncode(key);
      }
      StringBuffer new_prefix(key_prefix.size() + num_prefix.size() +
                              encoded.size() + key_suffix.size() + 4);
      new_prefix += key_prefix;
      if (numeric) new_prefix += num_prefix;
      new_prefix += encoded;
      new_prefix += key_suffix;
      new_prefix += "%5B";
      url_encode_array(ret, data, seen_arrs, String(),
                       new_prefix.detach(), String("%5D", AttachLiteral),
                       arg_sep);
    } else {
      if (!ret.empty()) {
        ret += arg_sep;
      }
      ret += key_prefix;
      if (numeric) {
        ret += num_prefix;
        ret += key;
      } else {
        ret += StringUtil::UrlEncode(key);
      }
      ret += key_suffix;
      ret += "=";
      if (data.isInteger() || data.is(KindOfBoolean)) {
        ret += String(data.toInt64());
      } else if (data.is(KindOfDouble)) {
        ret += String(data.toDouble());
      } else {
        ret += StringUtil::UrlEncode(data.toString());
      }
    }
  }
}
コード例 #9
0
ファイル: build.cpp プロジェクト: raynorpat/cake
 void flush()
 {
   if(!m_buffer.empty())
   {
     m_tool.push_back(new VariableString(m_buffer.c_str()));
     m_buffer.clear();
   }
 }
コード例 #10
0
static void append_line_no(StringBuffer &sb, const char *text,
                           int &line, const char *color, const char *end,
                           int lineFocus0, int charFocus0, int lineFocus1,
                           int charFocus1, const char **palette =
                           DebuggerClient::DefaultCodeColors) {
  TRACE(7, "debugger_base:append_line_no\n");
  const char *colorLineNo = palette[CodeColorLineNo * 2];
  const char *endLineNo = palette[CodeColorLineNo * 2 + 1];

  // beginning
  if (line && sb.empty()) {
    if (colorLineNo) color_line_no(sb, line, lineFocus0, lineFocus1,
                                   colorLineNo);
    sb.printf(DebuggerClient::LineNoFormat, line);
    if (endLineNo) sb.append(endLineNo);
  }

  // ending
  if (text == nullptr) {
    if (line) {
      if (colorLineNo) color_line_no(sb, line, lineFocus0, lineFocus1,
                                     colorLineNo);
      sb.append("(END)\n");
      if (endLineNo) sb.append(endLineNo);
    }
    return;
  }

  if (color) sb.append(color);

  if (line == 0) {
    sb.append(text);
  } else {
    const char *begin = text;
    const char *p = begin;
    for (; *p; p++) {
      if (*p == '\n') {
        ++line;
        sb.append(begin, p - begin);
        if (color) sb.append(ANSI_COLOR_END);
        sb.append('\n');
        if (colorLineNo) color_line_no(sb, line, lineFocus0, lineFocus1,
                                       colorLineNo);
        sb.printf(DebuggerClient::LineNoFormat, line);
        if (endLineNo) sb.append(endLineNo);
        if (color) sb.append(color);
        begin = p + 1;
      }
    }
    if (p - begin > 0) {
      sb.append(begin, p - begin);
    }
  }

  if (end) sb.append(end);
}
コード例 #11
0
ファイル: HttpUploader.cpp プロジェクト: fieldwind/syncsdk
int HttpUploader::upload(const StringBuffer& luid, InputStream* inputStream) 
{
    int status = 0;

    // safe checks
    if (!inputStream || !inputStream->getTotalSize()) {
        LOG.error("upload error: no data to transfer");
        return 1;
    }
    if (luid.empty() || syncUrl.empty()  || sourceURI.empty()) {
        LOG.error("upload error: some params are not set");
        return 2;
    }
    
    StringBuffer fullUrl = composeURL();
    URL url(fullUrl.c_str());
    HttpConnection* httpConnection = getHttpConnection();
   
    httpConnection->setCompression(false);
    status = httpConnection->open(url, HttpConnection::MethodPost);
    
    if (status) { 
        delete httpConnection;

        return status;
    }

    httpConnection->setKeepAlive(keepalive);
    httpConnection->setRequestChunkSize(maxRequestChunkSize);
   
    // Set headers (use basic auth)
    HttpAuthentication* auth = new BasicAuthentication(username, password);
    httpConnection->setAuthentication(auth);
    setRequestHeaders(luid, *httpConnection, *inputStream);
    
    // Send the HTTP request
    StringOutputStream response;
    status = httpConnection->request(*inputStream, response);
    LOG.debug("response returned = %s", response.getString().c_str());
    
    // Manage response headers
    if (useSessionID) {
        // Server returns the jsessionId in the Set-Cookie header, can be used for 
        // the subsequent calls of upload().
        StringBuffer hdr = httpConnection->getResponseHeader(HTTP_HEADER_SET_COOKIE);
        sessionID = httpConnection->parseJSessionId(hdr);
    }
    
    httpConnection->close();
    
    delete auth;
    delete httpConnection;
    return status;
}
コード例 #12
0
ファイル: HttpConnection.cpp プロジェクト: fieldwind/syncsdk
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;
    }
}
コード例 #13
0
ファイル: MHSyncItemInfo.cpp プロジェクト: fieldwind/syncsdk
time_t MHSyncItemInfo::getExportTimeForService(const char* serviceName)
{
    time_t serviceExportTime = -1;
    
    if (serviceName) {
        StringBuffer exportTimeStr = exportedServices.get(serviceName);
        
        if (exportTimeStr.empty() == false) {
            serviceExportTime = atol(exportTimeStr.c_str());
        }
    }

    return serviceExportTime;
}
コード例 #14
0
ファイル: FolderData.cpp プロジェクト: fieldwind/syncsdk
char* FolderData::format() {

    StringBuffer out;

    out.reserve(150);

    out = "<Folder>\n";
    if (name.length() > 0)
        out += XMLProcessor::makeElement(FOLDER_NAME, name);
    if (created.length() > 0)
        out += XMLProcessor::makeElement(FOLDER_CREATED, created);
    if (modified.length() > 0)
        out += XMLProcessor::makeElement(FOLDER_MODIFIED, modified);
    if (accessed.length() > 0)
        out += XMLProcessor::makeElement(FOLDER_ACCESSED, accessed);

    StringBuffer attributes;

    if (isHiddenPresent)
        attributes += XMLProcessor::makeElement(FOLDER_HIDDEN, hidden);
    if (isSystemPresent)
        attributes += XMLProcessor::makeElement(FOLDER_SYSTEM, system);
    if (isArchivedPresent)
        attributes += XMLProcessor::makeElement(FOLDER_ARCHIVED, archived);
    if (isDeletedPresent)
        attributes += XMLProcessor::makeElement(FOLDER_DELETE, deleted);
    if (isWritablePresent)
        attributes += XMLProcessor::makeElement(FOLDER_WRITABLE, writable);
    if (isReadablePresent)
        attributes += XMLProcessor::makeElement(FOLDER_READABLE, readable);
    if (isExecutablePresent)
        attributes += XMLProcessor::makeElement(FOLDER_EXECUTABLE, executable);

    if (!attributes.empty())
        out += XMLProcessor::makeElement(FOLDER_ATTRIBUTES, attributes);

    if (role.length() > 0)
        out += XMLProcessor::makeElement(FOLDER_ROLE, role);

    if (!(extended.isEmpty())){
        for(int i=0; i < extended.size(); i++){
            const char* temp =  ((FolderExt*)extended.get(i))->format();
            out += temp;
            delete [] temp;
        }
    }

    out += "</Folder>\n";
    return stringdup(out.c_str());
}
コード例 #15
0
static void append_line_no(StringBuffer &sb, const char *text,
                           int &line, const char *color, const char *end,
                           const char **palette =
                           DebuggerClient::DefaultCodeColors) {
  const char *colorLineNo = palette[CodeColorLineNo * 2];
  const char *endLineNo = palette[CodeColorLineNo * 2 + 1];

  // beginning
  if (line && sb.empty()) {
    if (colorLineNo) sb.append(colorLineNo);
    sb.printf(DebuggerClient::LineNoFormat, line);
    if (endLineNo) sb.append(endLineNo);
  }

  // ending
  if (text == NULL) {
    if (line) {
      if (colorLineNo) sb.append(colorLineNo);
      sb.append("(END)\n");
      if (endLineNo) sb.append(endLineNo);
    }
    return;
  }

  if (color) sb.append(color);

  if (line == 0) {
    sb.append(text);
  } else {
    const char *begin = text;
    const char *p = begin;
    for (; *p; p++) {
      if (*p == '\n') {
        sb.append(begin, p - begin);
        if (end) sb.append(end);
        sb.append('\n');
        if (colorLineNo) sb.append(colorLineNo);
        sb.printf(DebuggerClient::LineNoFormat, ++line);
        if (endLineNo) sb.append(endLineNo);
        if (color) sb.append(color);
        begin = p + 1;
      }
    }
    if (p - begin > 0) {
      sb.append(begin, p - begin);
    }
  }

  if (end) sb.append(end);
}
コード例 #16
0
ファイル: Configuration.cpp プロジェクト: offa/config4cpp
void
Configuration::mergeNames(
	const char *		scope,
	const char *		localName,
	StringBuffer &		fullyScopedName)
{
	if (scope[0] == '\0') {
		fullyScopedName = localName;
	} else if (localName[0] == '\0') {
		fullyScopedName = scope;
	} else {
		fullyScopedName.empty();
		fullyScopedName << scope << "." << localName;
	}
}
コード例 #17
0
BOOL CMediaHubSetting::OnInitDialog() {

    if (!ssconf) return FALSE;

    bool showAdvanced = true;
    CString s1;
    s1.LoadString(IDS_MEDIA_HUB_TITLE);
    SetWindowText(s1);
    CDialog::OnInitDialog();

    editFolder.SetLimitText  (EDIT_TEXT_MAXLENGTH);    
  
    // load string resources
    s1.LoadString(IDS_MEDIA_HUB_GROUP_FOLDER_LABEL);    SetDlgItemText(IDC_MEDIA_HUB_GROUP_FOLDER,       s1);    
    //s1.LoadString(IDS_CURRENT);             SetDlgItemText(IDC_MEDIA_HUB_STATIC_FOLDER,      s1);
    s1.LoadString(IDS_SELECT_FOLDER);       SetDlgItemText(IDC_MEDIA_HUB_BUT_SELECT,         s1);
    s1.LoadString(IDS_OK);                  SetDlgItemText(IDC_MEDIA_HUB_OK,                 s1);
    s1.LoadString(IDS_CANCEL);              SetDlgItemText(IDC_MEDIA_HUB_CANCEL,             s1);
    s1.LoadString(IDS_RESET_BUTTON);        SetDlgItemText(IDC_MEDIA_HUB_BUT_RESET,          s1);
    s1.LoadString(IDS_MEDIA_HUB_EXPLAIN_LABEL);  SetDlgItemText(IDC_MEDIA_HUB_EXPLAIN_LABEL, s1);
    
   
    StringBuffer path = ssconf->getCommonConfig()->getProperty(PROPERTY_MEDIAHUB_PATH);
    if (path.empty() == false) {
        return true;        
    }
    
    path = getFullMediaHubDefault();        
    WCHAR* wpath = toWideChar(path.c_str());
    s1 = wpath;
    delete [] wpath;
    SetDlgItemText(IDC_MEDIA_HUB_EDIT_FOLDER, s1);
           
    // disable windows xp theme, otherwise any color setting for groupbox
    // will be overriden by the theme settings
    if (((COutlookPluginApp*)AfxGetApp())->hLib){
        PFNSETWINDOWTHEME pfnSetWindowTheme =
            (PFNSETWINDOWTHEME)GetProcAddress(((COutlookPluginApp*)AfxGetApp())->hLib, "SetWindowTheme");        
        pfnSetWindowTheme (groupFolder.m_hWnd,    L" ", L" ");
        
    }   

    GetDlgItem(IDC_MEDIA_HUB_BUT_SELECT)->SetFocus();
    GetDlgItem(IDC_MEDIA_HUB_BUT_RESET)->EnableWindow(FALSE);

    return FALSE;
}
コード例 #18
0
ファイル: MHLabelsStore.cpp プロジェクト: fieldwind/syncsdk
bool MHLabelsStore::RemoveEntry(MHStoreEntry* entry)
{
    if (entry == NULL) {
        LOG.error("%s: invalid parameter", __FUNCTION__);
        return false;
    }
    
    MHLabelInfo* itemInfo = dynamic_cast<MHLabelInfo*>(entry);
    if (itemInfo == NULL) {
        LOG.error("%s: invalid parameter", __FUNCTION__);
        return false;
    }

    if (store_status != store_status_initialized) {
        LOG.error("%s: can't add entry: cache is not initialized", __FUNCTION__);
        return false;
    }
    
    
    StringBuffer sql;
    sql.sprintf(delete_row_id_stmt_fmt, store_name.c_str(), itemInfo->getLuid());
    
    if (sql.empty()) {
        LOG.error("%s: error formatting delete-entry statement", __FUNCTION__);
        return false;
    }
    
    //LOG.debug("%s: > SQL exec: '%s'", __FUNCTION__, sql.c_str());
    pthread_mutex_lock(&store_access_mutex);
    int ret = sqlite3_exec(db, sql.c_str(), NULL, NULL, NULL);
    int changes = sqlite3_changes(db);
    pthread_mutex_unlock(&store_access_mutex);
    
    if (ret != SQLITE_OK) {
        LOG.error("%s: error executing SQL statement: %s", __FUNCTION__, sqlite3_errmsg(db));
        return false;
    } else if (changes == 0) {
        LOG.info("%s: cannot remove item %u", __FUNCTION__, itemInfo->getLuid());
        return false;
    }
    else {
        cache_items_count = getCount();
        cache_items_count--;
        return true;
    }
}
コード例 #19
0
ファイル: MHLabelsStore.cpp プロジェクト: fieldwind/syncsdk
bool MHLabelsStore::UpdateEntry(MHStoreEntry* entry)
{
    int ret = SQLITE_OK;
   
    if (entry == NULL) {
        LOG.error("%s: invalid parameter", __FUNCTION__);
        return false;
    }
    
    MHSyncItemInfo* itemInfo = (MHSyncItemInfo*)entry;
    if (itemInfo == NULL) {
        LOG.error("%s: invalid parameter", __FUNCTION__);
        return false;
    }

    if (store_status != store_status_initialized) {
        LOG.error("%s: can't add entry: cache is not initialized", __FUNCTION__);
        
        return false;
    }

    StringBuffer sql = formatUpdateItemStmt(itemInfo);
    
    if (sql.empty()) {
        LOG.error("%s: error formatting cache update item statement", __FUNCTION__);
        
        return false;
    }
    
    //LOG.debug("%s: > SQL exec: '%s'", __FUNCTION__, sql.c_str());
    pthread_mutex_lock(&store_access_mutex);
    ret = sqlite3_exec(db, sql.c_str(), NULL, NULL, NULL);
    pthread_mutex_unlock(&store_access_mutex);
    
    if (ret != SQLITE_OK) {
        LOG.error("%s: error executing SQL statement: %s", __FUNCTION__, sqlite3_errmsg(db));
        
        return false;
    }

    return true;
}
コード例 #20
0
Cred* CredentialHandler::getClientCredential() {

    Authentication* auth = NULL;
    char* credential  = NULL;

    if (strcmp(clientAuthType, AUTH_TYPE_MD5) == 0) {
        credential = MD5CredentialData(username, password, clientNonce);
        auth = new Authentication(AUTH_TYPE_MD5, credential);
        // overwrite the username that for MD5 auth is the same as data
        auth->setUsername(username);
        auth->setPassword(password);
        if (credential) { delete [] credential; credential = NULL; }
    }
    else if (strcmp(clientAuthType, AUTH_TYPE_OAUTH) == 0) {
        OAuth2JsonParser jsonParser;
        StringBuffer creds = jsonParser.formatOAuth2CredentialData(oauth2Credentials.getAccessToken(), oauth2Credentials.getRefreshToken(),
                                                                   oauth2Credentials.getClientType(), oauth2Credentials.getExpiresIn(), oauth2AccessTokenSetTime);
        if (creds.empty()) {
            LOG.error("%s: could not set oauth2 auth credentials for SyncML request", __FUNCTION__);
            return NULL;
        }

        auth = new Authentication(AUTH_TYPE_OAUTH, creds.c_str());
        auth->setUsername(username);
    }
    else if (strcmp(clientAuthType, AUTH_TYPE_RADIUS_PROXY) == 0) {
        auth = new Authentication(AUTH_TYPE_RADIUS_PROXY, username, "Funambol");
    }
    else {
        auth = new Authentication(AUTH_TYPE_BASIC, username, password);
    }

    Cred* cred = new Cred(auth);

    deleteAuthentication(&auth);
    return cred;

}
コード例 #21
0
    void testSetItemStatus(){
        StringBuffer inFile = getTestFileFullPath(TEST_INPUT_DIR, TEST_FILE_NAME1);
        SyncItem* si = fmss->fakeFillSyncItem(&inFile, true);

        const WCHAR* wKey = si->getKey();
        const char* key = toMultibyte(wKey);
        fmss->setItemStatus(wKey, 200, "Add");
        ArrayList luidToSend = fmss->getLUIDArray();

        bool luidPresent = false;
        for (int i = 0; i < luidToSend.size(); i++){
            if( strcmp( ((StringBuffer*)luidToSend.get(i))->c_str(), key) == 0 ){
                luidPresent = true;
            }
        }
        CPPUNIT_ASSERT(luidPresent);

        int ret = fmss->endSync();
        CPPUNIT_ASSERT( ret == 0 );
    
        StringBuffer propval = fmss->fakeReadCachePropertyValue(inFile.c_str());
        CPPUNIT_ASSERT( !propval.empty() );
    }
コード例 #22
0
ファイル: MailMessage.cpp プロジェクト: ruphy/kfunambol
int MailMessage::parseHeaders(StringBuffer &rfcHeaders) {

    ArrayList lines;
    const StringBuffer *line;
    StringBuffer strReceived;
    bool receivedExtracted = false;
    LOG.debug("parseHeaders START");

    // Join header parts using \t or 8 blank
    StringBuffer joinlinetab("\t");
    rfcHeaders.replaceAll(joinlinetab, " ");

    StringBuffer joinlinespaces(newline);
    joinlinespaces+=" ";  // 8 blanks

    rfcHeaders.replaceAll(joinlinespaces, " ");

    rfcHeaders.split(lines, newline);

    // importance is set to "0" by default. Then there isn't anything modification
    // in the header, at the end of the loop the importance will be set to "3", default normal
    importance = "0";

    for ( line=(StringBuffer *)lines.front();
          line;
          line=(StringBuffer *)lines.next() ) {

        if( *line == "\r" )
            break;
        // The first empty line marks the end of the header section
        if( line->empty() ){
            break;
        }
        // Process the headers

        if( line->ifind(TO) == 0 ){
            to = MailMessage::decodeHeader(line->substr(TO_LEN));
        }
        else if( line->ifind(FROM) == 0 ) {
            from = MailMessage::decodeHeader(line->substr(FROM_LEN));
        }
        else if( line->ifind(CC) == 0 ) {
            cc = MailMessage::decodeHeader(line->substr(CC_LEN));
        }
        else if( line->ifind(BCC) == 0 ) {
            bcc = MailMessage::decodeHeader(line->substr(BCC_LEN));
        }
        else if ( line->ifind(DATE) == 0 ) {
            //subjectParsing = false;
            if( date.parseRfc822(line->substr(DATE_LEN)) ) {
                LOG.error("Error parsing date");
                return 500;
            }
        }
        else if( line->ifind(SUBJECT) == 0 ) {

            subject = MailMessage::decodeHeader(line->substr(SUBJECT_LEN));
            LOG.debug("SUBJECT: %s", subject.c_str());
        }
        else if( line->ifind(ENCODING) == 0 ) {  // it is here for single part only
            body.setEncoding(line->substr(ENCODING_LEN));
        }
        else if(line->ifind(MIMEVERS) == 0 ) {
            mimeVersion = line->substr(MIMEVERS_LEN);
        }
        else if(line->ifind(MESSAGEID) == 0 ) {
            messageId = line->substr(MESSAGEID_LEN);
        }
        else if(line->ifind(IMPORTANCE) == 0 ) {
            StringBuffer data = line->substr(IMPORTANCE_LEN);
            data.lowerCase();
            importance = convertImportance(data);
        }
        else if(line->ifind(X_PRIORITY) == 0 ) {
            if (importance == "0") {
                StringBuffer data = line->substr(X_PRIORITY_LEN);
                data.lowerCase();
                importance = convertXPriority(data);
            }            
        }
        else if( line->ifind(MIMETYPE) == 0 ) {

            StringBuffer sb = getTokenValue(line, MIMETYPE);

            if (sb.length() > 0)
                contentType = sb;

            sb.reset();
            sb = getTokenValue(line, "boundary=", false);

            if (sb.length() > 0) {
                boundary = sb;
            } else {
                body.setCharset(getTokenValue(line, CT_CHARSET));
            }
            /*

            size_t len = line->find(";") - MIMETYPE_LEN ;
            contentType = line->substr(MIMETYPE_LEN, len);

            // Save boundary for multipart
            size_t begin = line->ifind("boundary=");
            size_t end = StringBuffer::npos;

            if( begin != StringBuffer::npos ) {
                begin += strlen("boundary=\"");
                end = line->find("\"", begin) ;
                boundary = line->substr( begin, end-begin );
            }
            else {
                    begin=line->ifind(CT_CHARSET);
                if( begin != StringBuffer::npos ) {
                    begin += strlen(CT_CHARSET);
                    size_t end = begin;
                    size_t quote = line->find("\"", begin);
                    if (quote != StringBuffer::npos){
                        begin = quote + 1;
                        end = line->find("\"", begin) ;
                    }
                    else {
                        end = line->find(";", begin) ;
                        if (end == StringBuffer::npos) {
                            end = line->find(" ", begin);
                        }
                    }
                    body.setCharset( line->substr( begin, end-begin ) );
                }
            }
            */
        }
        else if(line->ifind(RECEIVED) == 0) {
            if (!receivedExtracted) {
                strReceived = line->substr(line->rfind(";") );

                if (!strReceived.empty()) {
                    received.parseRfc822(strReceived.substr(2));
                    receivedExtracted = true;
                }
                /*
                while (!strReceived.empty()) {
                    if (received.parseRfc822(strReceived.substr(2)) == 0) {
                        receivedExtracted = true;
                        break;
                    } else {
                        StringBuffer s(line->substr(line->rfind(strReceived.c_str())));
                        strReceived = line->substr(s.rfind(";"));
                    }
                }
                */

            }
        }
        else {
            headers.add(*(StringBuffer *)line);
        }

    }
    // If received was not found, copy send date
    if( received == BasicTime() ){
        received = date;
    }

    // if the importance is never set we put the importance to 3, normal
    if (importance == "0") {
        importance = "3";
    }

    LOG.debug("parseHeaders END");

    // FIXME: should check for mandatory headers before return 0
    return 0;
}
コード例 #23
0
ファイル: MailMessage.cpp プロジェクト: ruphy/kfunambol
StringBuffer MailMessage::decodeHeader(StringBuffer line) {

    if (!line || line.empty()) {
        return line;
    }

    size_t startPos = 0;
    StringBuffer ret;
    StringBuffer charset;
    while( (startPos = line.find("=?", startPos)) != StringBuffer::npos) {
        // Skip the '=?'
        startPos += 2;
        // Find the first '?'
        size_t firstMark = line.find("?", startPos);
        if (firstMark == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }
        // Find the second '?'
        size_t secondMark = line.find("?", firstMark+1);
        if (secondMark == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }
        // Find the final '?='
        size_t endPos = line.find("?=", secondMark+1);
        if (endPos == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }

        charset = line.substr(startPos, firstMark - startPos);
        StringBuffer encoding = line.substr(firstMark+1, secondMark - (firstMark + 1));
        StringBuffer text = line.substr(secondMark+1, endPos - (secondMark + 1));

        if (encoding.icmp("Q")) {
            // quoted-printable
            text.replaceAll("_", " ");
            char* dec = qp_decode(text);
            if (startPos >= 2 &&  ret.length() == 0) {
                ret += line.substr(0, startPos - 2);
            }

            ret += dec;
            delete [] dec;
        }
        else if (encoding.icmp("B")){
        // base64
            char* dec = new char[text.length()];
            int len = b64_decode((void *)dec, text);
            dec[len]=0;
            if (startPos >= 2 &&  ret.length() == 0) {
                ret += line.substr(0, startPos - 2);
            }
            ret += dec;
            delete [] dec;
        }

        startPos = endPos;
    }

    if (ret.length() == 0) {
        ret += line;
    }

    WCHAR* wret = toWideChar(ret, charset);
    ret.set(NULL);
    char* t = toMultibyte(wret);
    ret.set(t);
    if (wret) {delete [] wret;}
    if (t) {delete [] t;}
    return ret;
}
コード例 #24
0
const int FConnection::startConnection(const StringBuffer& aIAPName)
{
    LOG.info("Starting new connection...");
    LOG.debug("Looking for '%s' IAP name", aIAPName.c_str());

    iLastError = KErrNone;
    StringBuffer errMsg;
    TCommDbConnPref prefs;

    prefs.SetDirection(ECommDbConnectionDirectionUnknown);


    if (aIAPName == "Default") {
        //
        // Use the default IAP without prompting the user
        //
        prefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);
        prefs.SetIapId(0);
    }
    else if (aIAPName.empty() || aIAPName == "Ask") {
        //
        // Prompt user for IAP selection
        //
    }
    else {
        //
        // Search for the desired IAP. If not found, will prompt the user.
        //
        TInt iapID = GetIAPIDFromName(aIAPName);
        if (iapID >= 0) {
            LOG.debug("SetDialogPreference");
            prefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);
            prefs.SetIapId(iapID);
        }
        else {
            LOG.debug("IAP '%s' not found!", aIAPName.c_str());
        }
    }


/*
 * **** TODO: check if we need this! ****
 In S60 3rd Edition, enabling/disabling the inactivity timer will require
 the NetworkControl capability, which is only accessed via Symbian
 partner.
 */
//#if !defined(__SERIES60_3X__) || defined(__S60_3X_NET_CTRL__)
//    // Disable inactivity timer, otherwise inactive connection is closed
//    // within few seconds if there are no activity (e.g sockets)
//    iConnection.SetOpt(KCOLProvider, KConnDisableTimers, ETrue);
//#endif


    // Opens the connection
    openConnection();

    // Start connection
    iLastError = iConnection.Start(prefs);
    if (iLastError != KErrNone) {
        errMsg.sprintf("FConnection error: unable to start connection (code %d)", iLastError);
        LOG.debug("Goto retry");
        goto retry;
    }

    // Save the IAP ID & name of the active connection.
    // Query the CommDb database for the IAP ID in use.
    _LIT(KIAPSettingName, "IAP\\Id");
    iConnection.GetIntSetting(KIAPSettingName, iIAP);
    iIAPName = GetIAPNameFromID(iIAP);
    LOG.debug("Current active IAP ID = %d, name = '%s'", iIAP, iIAPName.c_str());
    //
    // TODO: should we persist the iIAPName in the config, here?
    //

    iRetryConnection = 0;
    return 0;


retry:

    LOG.error("%s", errMsg.c_str());

    if (iIAPName.empty() || iIAPName == "Ask") {
        LOG.debug("Connection error and no IAP stored: don't retry");
        return iLastError;
    }

    LOG.debug("About to retry...");
    if (iRetryConnection < MAX_RETRY_CONNECTION) {
        iRetryConnection ++;
        LOG.info("Retry connection (%d time)...", iRetryConnection);
        startConnection(iIAPName);
    }
    else {
        LOG.error("FConnection: %d connection failed", iRetryConnection);
    }
    return iLastError;
}
コード例 #25
0
ファイル: HttpConnection.cpp プロジェクト: fieldwind/syncsdk
int HttpConnection::readResponse(OutputStream& os)
{
    char* responseBuffer  = NULL;
    char* zResponseBuffer = NULL;
    bool writeDataAtOnce = false;
    DWORD read = 0;
    int ret = 0;
    bool inflate = false;

#ifdef USE_ZLIB
    DWORD contentLength = 0;
    DWORD uncompressedContentLength = 0;
    DWORD size   = 512;
  
    if (compression_enabled) {

        //
        // get response length
        //
        StringBuffer val = getResponseHeader(HTTP_HEADER_CONTENT_LENGTH);
        if (val.empty()) {
            LOG.error("error reading %s from HTTP headers", HTTP_HEADER_CONTENT_LENGTH);
            return StatusInvalidParam;
        }
        contentLength = atoi(val.c_str());
        if (contentLength <= 0) {
            LOG.error("error reading %s from HTTP headers: %d", HTTP_HEADER_CONTENT_LENGTH, contentLength);
            return StatusInvalidParam;
        }

        //
        // get response encoding
        //
        val = getResponseHeader(HTTP_HEADER_CONTENT_ENCODING);
        if (val.empty()) {
            LOG.error("error reading %s from HTTP headers", HTTP_HEADER_CONTENT_ENCODING);
            return StatusInvalidParam;
        }
        if (val == "deflate") {
            inflate = true;
        }

        if (inflate) {
            //
            // get uncompressed content length
            //
            val = getResponseHeader(HTTP_HEADER_UNCOMPRESSED_CONTENT_LENGTH);
            if (val.empty()) {
                LOG.error("error reading %s from HTTP headers", HTTP_HEADER_UNCOMPRESSED_CONTENT_LENGTH);
                return StatusInvalidParam;
            }
            uncompressedContentLength = atoi(val.c_str());
            if (uncompressedContentLength <= 0) {
                LOG.error("error reading %s from HTTP headers: %d", HTTP_HEADER_UNCOMPRESSED_CONTENT_LENGTH, uncompressedContentLength);
                return StatusInvalidParam;
            }

            zResponseBuffer = new char[contentLength + 1];
        }
    }
#endif
    
    // Allocate a block of memory for response read.
    responseBuffer = new char[responseChunkSize + 1];
    memset(responseBuffer, 0, responseChunkSize);
    int zOffset = 0;
    // TODO: if enabled to check the connection, sometimes it crashes :( 
    // HttpConnectionTimer* th = new HttpConnectionTimer(&zOffset, req, responseTimeout);
    // th->start();
    do {
        if (!InternetReadFile(req, (LPVOID)responseBuffer, responseChunkSize, &read)) {
            ret = StatusReadingError;
            break;
        }

        if (read > 0) {
            if (inflate) {
                memcpy(zResponseBuffer + zOffset, responseBuffer, read);
                zOffset += read;
            } else {
                os.write(responseBuffer, read);
                zOffset += read;
                fireTransportEvent(read, DATA_RECEIVED);
            }
        }
    } while (read);
    
    // th->softTerminate();
    
    delete [] responseBuffer; 
    

    if (inflate) {
        uLong uncomprLen = uncompressedContentLength;
        Bytef* uncompr = new Bytef[uncompressedContentLength + 1];

        //
        // Decompresses the source buffer into the destination buffer.
        //
        int err = uncompress(uncompr, &uncomprLen, (Bytef*)zResponseBuffer, contentLength);

        if (err == Z_OK) {
            char* response = (char*)uncompr;
            response[uncompressedContentLength] = 0;
            os.write(response, uncompressedContentLength);
        } else  {
            LOG.error("Error in zlib uncompress: %s", zError(err));
            ret = StatusInternalError;
        }
        delete [] uncompr;
    }


    delete [] zResponseBuffer;
    return ret;
}
コード例 #26
0
ファイル: ext_url.cpp プロジェクト: Alienfeel/hhvm
static void url_encode_array(StringBuffer &ret, CVarRef varr,
                             std::set<void*> &seen_arrs,
                             const String& num_prefix, const String& key_prefix,
                             const String& key_suffix, const String& arg_sep) {
  void *id = varr.is(KindOfArray) ?
    (void*)varr.getArrayData() : (void*)varr.getObjectData();
  if (!seen_arrs.insert(id).second) {
    return; // recursive
  }

  Array arr;
  if (varr.is(KindOfObject)) {
    Object o = varr.toObject();
    arr = (o.objectForCall()->isCollection()) ?
      varr.toArray() :
      f_get_object_vars(o).toArray();
  } else {
    arr = varr.toArray();
  }

  for (ArrayIter iter(arr); iter; ++iter) {
    Variant data = iter.second();
    if (data.isNull() || data.isResource()) continue;

    String key = iter.first();
    bool numeric = key.isNumeric();

    if (data.is(KindOfArray) || data.is(KindOfObject)) {
      String encoded;
      if (numeric) {
        encoded = key;
      } else {
        encoded = StringUtil::UrlEncode(key);
      }
      StringBuffer new_prefix(key_prefix.size() + num_prefix.size() +
                              encoded.size() + key_suffix.size() + 4);
      new_prefix.append(key_prefix);
      if (numeric) new_prefix.append(num_prefix);
      new_prefix.append(encoded);
      new_prefix.append(key_suffix);
      new_prefix.append("%5B");
      url_encode_array(ret, data, seen_arrs, String(),
                       new_prefix.detach(), String("%5D", CopyString),
                       arg_sep);
    } else {
      if (!ret.empty()) {
        ret.append(arg_sep);
      }
      ret.append(key_prefix);
      if (numeric) {
        ret.append(num_prefix);
        ret.append(key);
      } else {
        ret.append(StringUtil::UrlEncode(key));
      }
      ret.append(key_suffix);
      ret.append("=");
      if (data.isInteger() || data.is(KindOfBoolean)) {
        ret.append(String(data.toInt64()));
      } else if (data.is(KindOfDouble)) {
        ret.append(String(data.toDouble()));
      } else {
        ret.append(StringUtil::UrlEncode(data.toString()));
      }
    }
  }
}
コード例 #27
0
static void url_encode_array(StringBuffer &ret, const Variant& varr,
                             std::set<void*> &seen_arrs,
                             const String& num_prefix, const String& key_prefix,
                             const String& key_suffix, const String& arg_sep,
                             bool encode_plus = true) {
  void *id = varr.isArray() ?
    (void*)varr.getArrayData() : (void*)varr.getObjectData();
  if (!seen_arrs.insert(id).second) {
    return; // recursive
  }

  // Allow multiple non-recursive references to the same array/object
  SCOPE_EXIT { seen_arrs.erase(id); };

  Array arr;
  if (varr.is(KindOfObject)) {
    Object o = varr.toObject();
    arr = o->isCollection()
      ? varr.toArray()
      : HHVM_FN(get_object_vars(o));
  } else {
    arr = varr.toArray();
  }

  for (ArrayIter iter(arr); iter; ++iter) {
    Variant data = iter.second();
    if (data.isNull() || data.isResource()) continue;

    String key = iter.first();
    bool numeric = key.isNumeric();

    if (data.isArray() || data.is(KindOfObject)) {
      String encoded;
      if (numeric) {
        encoded = key;
      } else {
        encoded = StringUtil::UrlEncode(key, encode_plus);
      }
      StringBuffer new_prefix(key_prefix.size() + num_prefix.size() +
                              encoded.size() + key_suffix.size() + 4);
      new_prefix.append(key_prefix);
      if (numeric) new_prefix.append(num_prefix);
      new_prefix.append(encoded);
      new_prefix.append(key_suffix);
      new_prefix.append("%5B");
      url_encode_array(ret, data, seen_arrs, String(),
                       new_prefix.detach(), String("%5D", CopyString),
                       arg_sep);
    } else {
      if (!ret.empty()) {
        ret.append(arg_sep);
      }
      ret.append(key_prefix);
      if (numeric) {
        ret.append(num_prefix);
        ret.append(key);
      } else {
        ret.append(StringUtil::UrlEncode(key, encode_plus));
      }
      ret.append(key_suffix);
      ret.append("=");
      if (data.isInteger() || data.is(KindOfBoolean)) {
        ret.append(String(data.toInt64()));
      } else if (data.is(KindOfDouble)) {
        ret.append(String(data.toDouble()));
      } else {
        ret.append(StringUtil::UrlEncode(data.toString(), encode_plus));
      }
    }
  }
}
コード例 #28
0
void CPicturesSettings::OnCbnSelchangePicturesComboSynctype()
{
    // Supported data format
    StringBuffer supportedData;
    
    CString ss(" "), ss1;        
    ss1.LoadString(IDS_SUPPORTED_FORMAT);
    ss.Append(ss1);
    
    CString And;
    And.LoadString(IDS_STRING_AND);
    StringBuffer and(" ");
    and.append(ConvertToChar(And));
    and.append(" ");
       
    
    StringBuffer data = ssconf->getProperty(PROPERTY_EXTENSION);    
    if (data.empty() == false) {
       
        supportedData = ConvertToChar(ss);
        
        StringBuffer data = ssconf->getProperty(PROPERTY_EXTENSION);    
        data.upperCase();
        supportedData.append(data);
        
        int val = supportedData.rfind(",.");
        if (val != StringBuffer::npos) {
            supportedData.replace(",.", and.c_str(), val);
        }
        supportedData.replaceAll(",.",", ");
        supportedData.replaceAll(".","");  
        supportedData.append(".");
    }
   
    CString suppData = supportedData;

    int index = 0;
    if (lstSyncType.GetCount() > 1) {
        index = lstSyncType.GetCurSel();
    } else {
        // Fixed, 1 synctype only, get from config.
        index = getSyncTypeIndex(ssconf->getSync());
    }

    CString s1;
    switch (index) {
        case 0:
            s1.LoadString(IDS_TWO_WAY_LABEL_PICT_SUMMARY);
            s1.Append(suppData);
            SetDlgItemText(IDC_PICTURES_SYNC_DIRECTION_LABEL, s1);
            break;
        case 1:
            s1.LoadString(IDS_DOWNLOAD_ONLY_LABEL_PICT_SUMMARY);        
            s1.Append(suppData);
            SetDlgItemText(IDC_PICTURES_SYNC_DIRECTION_LABEL, s1);
            break;
        case 2:
            s1.LoadString(IDS_UPLOAD_ONLY_LABEL_PICT_SUMMARY);
            s1.Append(suppData);
            SetDlgItemText(IDC_PICTURES_SYNC_DIRECTION_LABEL, s1);
            break;
    }
}
コード例 #29
0
    /*
     * Resolve the name of a function. If the function already has a name
     * listed, then it is skipped. Otherwise an intelligent name is guessed to
     * assign to the function's displayAtom field
     */
    JSAtom *resolveFun(ParseNode *pn, HandleAtom prefix) {
        JS_ASSERT(pn != NULL && pn->isKind(PNK_FUNCTION));
        RootedFunction fun(cx, pn->pn_funbox->function());

        StringBuffer buf(cx);
        this->buf = &buf;

        /* If the function already has a name, use that */
        if (fun->displayAtom() != NULL) {
            if (prefix == NULL)
                return fun->displayAtom();
            if (!buf.append(prefix) ||
                !buf.append("/") ||
                !buf.append(fun->displayAtom()))
                return NULL;
            return buf.finishAtom();
        }

        /* If a prefix is specified, then it is a form of namespace */
        if (prefix != NULL && (!buf.append(prefix) || !buf.append("/")))
            return NULL;

        /* Gather all nodes relevant to naming */
        ParseNode *toName[MaxParents];
        size_t size;
        ParseNode *assignment = gatherNameable(toName, &size);

        /* If the function is assigned to something, then that is very relevant */
        if (assignment) {
            if (assignment->isAssignment())
                assignment = assignment->pn_left;
            if (!nameExpression(assignment))
                return NULL;
        }

        /*
         * Other than the actual assignment, other relevant nodes to naming are
         * those in object initializers and then particular nodes marking a
         * contribution.
         */
        for (int pos = size - 1; pos >= 0; pos--) {
            ParseNode *node = toName[pos];

            if (node->isKind(PNK_COLON)) {
                ParseNode *left = node->pn_left;
                if (left->isKind(PNK_NAME) || left->isKind(PNK_STRING)) {
                    if (!appendPropertyReference(left->pn_atom))
                        return NULL;
                } else if (left->isKind(PNK_NUMBER)) {
                    if (!appendNumericPropertyReference(left->pn_dval))
                        return NULL;
                }
            } else {
                /*
                 * Don't have consecutive '<' characters, and also don't start
                 * with a '<' character.
                 */
                if (!buf.empty() && *(buf.end() - 1) != '<' && !buf.append("<"))
                    return NULL;
            }
        }

        /*
         * functions which are "genuinely anonymous" but are contained in some
         * other namespace are rather considered as "contributing" to the outer
         * function, so give them a contribution symbol here.
         */
        if (!buf.empty() && *(buf.end() - 1) == '/' && !buf.append("<"))
            return NULL;
        if (buf.empty())
            return NULL;

        JSAtom *atom = buf.finishAtom();
        if (!atom)
            return NULL;
        fun->setGuessedAtom(atom);
        return atom;
    }
コード例 #30
0
BOOL CPicturesSettings::OnInitDialog() {

    if (!ssconf) return FALSE;
    
    bool showAdvanced = true;
    CString s1;
    s1.LoadString(IDS_PICTURES_DETAILS);
    SetWindowText(s1);
    CDialog::OnInitDialog();

    editSyncType.SetLimitText(EDIT_TEXT_MAXLENGTH);
    editFolder.SetLimitText  (EDIT_TEXT_MAXLENGTH);    

    // Load the syncmodes in the editbox/dropdown
    loadSyncModesBox(PICTURE_);

    // load string resources
    s1.LoadString(IDS_SYNC_DIRECTION);      SetDlgItemText(IDC_PICTURES_GROUP_DIRECTION,    s1);
    s1.LoadString(IDS_PICTURES_FOLDER);     SetDlgItemText(IDC_PICTURES_GROUP_FOLDER,       s1);
    s1.LoadString(IDS_SELECT_FOLDER);       SetDlgItemText(IDC_PICTURES_BUT_SELECT,         s1);
    s1.LoadString(IDS_OK);                  SetDlgItemText(IDC_PICTURES_OK,                 s1);
    s1.LoadString(IDS_CANCEL);              SetDlgItemText(IDC_PICTURES_CANCEL,             s1);
    
    
    // Sync type
    lstSyncType.SetCurSel(getSyncTypeIndex(ssconf->getSync()));
    OnCbnSelchangePicturesComboSynctype();

    int id = getPicturesSyncTypeID(ssconf->getSync());
    s1.LoadString(id);
    SetDlgItemText(IDC_PICTURES_EDIT_SYNCTYPE, s1);

    // Pictures folder path
    
    StringBuffer path = ssconf->getProperty(PROPERTY_MEDIAHUB_PATH);
    if (path.empty()) {
        // If empty, set the default path for pictures (shell folder)
        path = getDefaultMyDocumentsPath();
        path.append("\\");
        path.append(MEDIA_HUB_DEFAULT_FOLDER);        
        ssconf->setProperty(PROPERTY_MEDIAHUB_PATH, path.c_str());
    }
    WCHAR* wpath = toWideChar(path.c_str());
    s1 = wpath;
    delete [] wpath;
    SetDlgItemText(IDC_PICTURES_EDIT_FOLDER, s1);    
    
    butSelectFolder.EnableWindow(FALSE);   
 

    // disable windows xp theme, otherwise any color setting for groupbox
    // will be overriden by the theme settings
    if (((COutlookPluginApp*)AfxGetApp())->hLib){
        PFNSETWINDOWTHEME pfnSetWindowTheme =
            (PFNSETWINDOWTHEME)GetProcAddress(((COutlookPluginApp*)AfxGetApp())->hLib, "SetWindowTheme");
        pfnSetWindowTheme (groupDirection.m_hWnd, L" ", L" ");
        pfnSetWindowTheme (groupFolder.m_hWnd,    L" ", L" ");        
    }
    GetDlgItem(IDC_PICTURES_OK)->SetFocus();

    return FALSE;
}