Example #1
0
 virtual void format(const Value &value, std::function<void(const char *, size_t)> output) const
 {
     String str;
     switch (value.type()) {
     case Value::Type_Invalid:
     case Value::Type_Undefined:
         output("null", 4);
         break;
     case Value::Type_Boolean:
         if (value.toBool()) {
             output("true", 4);
         } else {
             output("false", 5);
         }
         break;
     case Value::Type_Integer: {
         char buf[128];
         const size_t w = snprintf(buf, sizeof(buf), "%d", value.toInteger());
         output(buf, w);
         break; }
     case Value::Type_Double: {
         char buf[128];
         const size_t w = snprintf(buf, sizeof(buf), "%g", value.toDouble());
         output(buf, w);
         break; }
     case Value::Type_String:
         str = value.toString();
         break;
     case Value::Type_Custom:
         str = value.toCustom()->toString();
         break;
     case Value::Type_Map: {
         const auto end = value.end();
         List<String> strings;
         ++indent;
         for (auto it = value.begin(); it != end; ++it) {
             // printf("%*s" "%s", indent, " ", string);
             String s = String::format<128>("%*s%s: ", indent - 1, " ", it->first.constData());
             format(it->second, [&s](const char *ch, size_t len) {
                     s.append(ch, len);
                 });
             output(s.constData(), s.size());
             output("\n", 1);
         }
         --indent;
         break; }
     case Value::Type_List: {
         const auto end = value.listEnd();
         output("[ ", 1);
         bool first = true;
         for (auto it = value.listBegin(); it != end; ++it) {
             if (!first) {
                 output(", ", 1);
             } else {
                 first = false;
             }
             format(*it, output);
         }
         output(" ]", 2);
         break; }
     case Value::Type_Date:
         str = String::formatTime(value.toDate().time());
         break;
     }
     if (!str.isEmpty())
         output(str.constData(), str.size());
 }
int main(int argc, char** argv)
{
	initModule_nonfree();
	FileStorage fs;

	if (!fs.open(DATABASE_FILENAME, FileStorage::READ))
	{
		/// Local Features Detection
		cout << "Detecting all Local Features" << endl;
		detecLocalFeatures();
		cout << "Done\n" << endl;

		/// Gather Features
		cout << "Gathering all Local Features" << endl;
		gatherLocalFeatures();
		cout << "Done\n" << endl;

		/// Cluster Features
		cout << "Clustering Features" << endl;
		clusterFeatures();
		cout << "Done\n" << endl;

		/// Write Vocabulary
		cout << "Saving Vocabulary" << endl;
		saveVocabulary();
		cout << "Done\n" << endl;
	}
	else
	{
		/// Load Vocabulary
		cout << "Loading Vocabulary" << endl;
		loadVocabulary();
		cout << "Done\n" << endl;
	}

	if (!fs.open(INDEXES_FILENAME, FileStorage::READ))
	{
		/// Compute Descriptors
		cout << "Computing Descriptors" << endl;
		computeDescriptors();
		cout << "Done\n" << endl;

		/// Save Descriptors
		cout << "Saving Descriptors" << endl;
		saveDescriptors();
		cout << "Done\n" << endl;

		/// Compute Occurrences
		cout << "Computing Occurrences" << endl;
		computeOccurrences();
		cout << "Done\n" << endl;

		/// Compute Weights
		cout << "Computing Weights" << endl;
		computeWeights();
		cout << "Done\n" << endl;

		/// Save Indexes
		cout << "Saving Indexes" << endl;
		saveIndexes();
		cout << "Done\n" << endl;
	}
	else
	{
		/// Load Descriptors
		cout << "Loading Descriptors" << endl;
		loadDescriptors();
		cout << "Done\n" << endl;

		/// Load Indexes
		cout << "Loading Indexes" << endl;
		loadIndexes();
		cout << "Done\n" << endl;
	}

	if (!fs.open(CLASSIFIERS_FILENAME, FileStorage::READ))
	{
		/// Train Classifier
		cout << "Training Classifier" << endl;
		trainClassifier();
		cout << "Done\n" << endl;
	}
	else
	{
		/// Load Classifier
		cout << "Loading Classifier" << endl;
		loadClassifier();
		cout << "Done\n" << endl;
	}

	if (!existFile(CONFUSION_MATRIX_FILENAME))
	{
		/// Create Confusion Matrix
		cout << "Creating Confusion Matrix" << endl;
		createConfusionMatrix();
		saveConfusionMatrix();
		cout << "Done\n" << endl;
	}
	else loadConfusionMatrix();

	/// Print Confusion Matrix
	showConfusionMatrix();
	cout << endl;

	/// Create Confusion Table
	cout << "Creating Confusion Table" << endl;
	createConfusionTable();
	cout << "Done\n" << endl;

	//showTablesOfConfusion();

	/// Create Average Table of Confusion
	cout << "Creating Average Table of Confusion" << endl;
	createAverageTableOfConfusion();
	cout << "Done\n" << endl;

	showAverageTableOfConfusion();
	showStatistics();

	cout << "\n\n\nFinding Category" << endl;
	Mat img;
	openImage(TEST_IMG_FILENAME, img);
	vector<KeyPoint> keypoints;
	detector->detect(img, keypoints);
	Mat descriptor;
	bowExtractor.compute(img, keypoints, descriptor);
	int catIndex = (int) svm.predict(descriptor);

	cout << "Image Category: " << categories[catIndex] << endl;
	cout << "Done\n" << endl;

	cout << "Calculating Nearest Neighbors" << endl;

	vector<int> neighbors = nearestNeighbors(descriptor);
	neighbors = nearestNeighborsCat(neighbors, catIndex);

	imshow("Original", img);

	for (int i = 0; i < NUMBER_OF_FILES_RETRIVED; i++)
	{
		String windowName = "Nearest Neighbor ";
		windowName.append(to_string(i));
		imshow(windowName, getImage(neighbors[i]));
	}

	cout << "Done\n" << endl;

	waitKey(0);
	return 0;
}
Example #3
0
int main(int argc, char** argv)
{
    RemoveCrashDump removeCrashDump;
#ifdef OS_Darwin
    struct rlimit rlp;
    if (getrlimit(RLIMIT_NOFILE, &rlp) == 0) {
        if (rlp.rlim_cur < 1000) {
            rlp.rlim_cur = 1000;
            setrlimit(RLIMIT_NOFILE, &rlp);
        }
    }
#endif

    {
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_getstacksize(&attr, &defaultStackSize);
        pthread_attr_destroy(&attr);
        if (defaultStackSize < 1024 * 1024 * 4) { // 4 megs should be enough for everyone right?
            defaultStackSize = 1024 * 1024 * 4;
        }
    }

    Rct::findExecutablePath(*argv);

    struct option opts[] = {
        { "help", no_argument, 0, 'h' },
        { "version", no_argument, 0, 2 },
        { "include-path", required_argument, 0, 'I' },
        { "isystem", required_argument, 0, 's' },
        { "define", required_argument, 0, 'D' },
        { "log-file", required_argument, 0, 'L' },
        { "crash-dump-file", required_argument, 0, 19 },
        { "setenv", required_argument, 0, 'e' },
        { "no-Wall", no_argument, 0, 'W' },
        { "Weverything", no_argument, 0, 'u' },
        { "cache-AST", required_argument, 0, 'A' },
        { "verbose", no_argument, 0, 'v' },
        { "job-count", required_argument, 0, 'j' },
        { "header-error-job-count", required_argument, 0, 'H' },
        { "test", required_argument, 0, 't' },
        { "test-timeout", required_argument, 0, 'z' },
        { "clean-slate", no_argument, 0, 'C' },
        { "disable-sighandler", no_argument, 0, 'x' },
        { "silent", no_argument, 0, 'S' },
        { "exclude-filter", required_argument, 0, 'X' },
        { "socket-file", required_argument, 0, 'n' },
        { "config", required_argument, 0, 'c' },
        { "no-rc", no_argument, 0, 'N' },
        { "data-dir", required_argument, 0, 'd' },
        { "ignore-printf-fixits", no_argument, 0, 'F' },
        { "no-unlimited-errors", no_argument, 0, 'f' },
        { "block-argument", required_argument, 0, 'G' },
        { "no-spell-checking", no_argument, 0, 'l' },
        { "large-by-value-copy", required_argument, 0, 'r' },
        { "disallow-multiple-sources", no_argument, 0, 'm' },
        { "no-startup-project", no_argument, 0, 'o' },
        { "no-no-unknown-warnings-option", no_argument, 0, 'Y' },
        { "ignore-compiler", required_argument, 0, 'b' },
        { "watch-system-paths", no_argument, 0, 'w' },
        { "rp-visit-file-timeout", required_argument, 0, 'Z' },
        { "rp-indexer-message-timeout", required_argument, 0, 'T' },
        { "rp-connect-timeout", required_argument, 0, 'O' },
        { "rp-connect-attempts", required_argument, 0, 3 },
        { "rp-nice-value", required_argument, 0, 'a' },
        { "thread-stack-size", required_argument, 0, 'k' },
        { "suspend-rp-on-crash", no_argument, 0, 'q' },
        { "rp-log-to-syslog", no_argument, 0, 7 },
        { "start-suspended", no_argument, 0, 'Q' },
        { "separate-debug-and-release", no_argument, 0, 'E' },
        { "max-crash-count", required_argument, 0, 'K' },
        { "completion-cache-size", required_argument, 0, 'i' },
        { "completion-no-filter", no_argument, 0, 8 },
        { "extra-compilers", required_argument, 0, 'U' },
        { "allow-Wpedantic", no_argument, 0, 'P' },
        { "enable-compiler-manager", no_argument, 0, 'R' },
        { "enable-NDEBUG", no_argument, 0, 'g' },
        { "progress", no_argument, 0, 'p' },
        { "max-file-map-cache-size", required_argument, 0, 'y' },
#ifdef OS_FreeBSD
        { "filemanager-watch", no_argument, 0, 'M' },
#else
        { "no-filemanager-watch", no_argument, 0, 'M' },
#endif
        { "no-filemanager", no_argument, 0, 15 },
        { "no-file-lock", no_argument, 0, 13 },
        { "pch-enabled", no_argument, 0, 14 },
        { "no-filesystem-watcher", no_argument, 0, 'B' },
        { "arg-transform", required_argument, 0, 'V' },
        { "no-comments", no_argument, 0, 1 },
#ifdef RTAGS_HAS_LAUNCHD
        { "launchd", no_argument, 0, 4 },
#endif
        { "inactivity-timeout", required_argument, 0, 5 },
        { "daemon", no_argument, 0, 6 },
        { "log-file-log-level", required_argument, 0, 9 },
        { "watch-sources-only", no_argument, 0, 10 },
        { "debug-locations", no_argument, 0, 11 },
        { "validate-file-maps", no_argument, 0, 16 },
        { "tcp-port", required_argument, 0, 12 },
        { "rp-path", required_argument, 0, 17 },
        { "log-timestamp", no_argument, 0, 18 },
        { "root", required_argument, 0, 20 },
        { 0, 0, 0, 0 }
    };
    const String shortOptions = Rct::shortOptions(opts);
    if (getenv("RTAGS_DUMP_UNUSED")) {
        String unused;
        for (int i=0; i<26; ++i) {
            if (!shortOptions.contains('a' + i))
                unused.append('a' + i);
            if (!shortOptions.contains('A' + i))
                unused.append('A' + i);
        }
        printf("Unused: %s\n", unused.constData());
        for (int i=0; opts[i].name; ++i) {
            if (opts[i].name) {
                if (!opts[i].val) {
                    printf("No shortoption for %s\n", opts[i].name);
                } else if (opts[i].name[0] != opts[i].val) {
                    printf("Not ideal option for %s|%c\n", opts[i].name, opts[i].val);
                }
            }
        }
        return 0;
    }

    bool daemon = false;
    List<String> argCopy;
    List<char*> argList;
    {
        bool norc = false;
        Path rcfile = Path::home() + ".rdmrc";
        opterr = 0;

        StackBuffer<128, char*> originalArgv(argc);
        memcpy(originalArgv, argv, sizeof(char*) * argc);
        /* getopt will molest argv by moving pointers around when it sees
         * fit. Their idea of an optional argument is different from ours so we
         * have to take a copy of argv before they get their sticky fingers all
         * over it.
         *
         * We think this should be okay for an optional argument:
         * -s something
         *
         * They only populate optarg if you do:
         * -ssomething.
         *
         * We don't want to copy argv into argList before processing rc files
         * since command line args should take precedence over things in rc
         * files.
         *
         */

        while (true) {
            const int c = getopt_long(argc, argv, shortOptions.constData(), opts, 0);
            if (c == -1)
                break;
            switch (c) {
            case 'N':
                norc = true;
                break;
            case 'c':
                rcfile = optarg;
                break;
            default:
                break;
            }
        }
        opterr = 1;
        argList.append(argv[0]);
        if (!norc) {
            String rc = Path("/etc/rdmrc").readAll();
            if (!rc.isEmpty()) {
                for (const String& s : rc.split('\n')) {
                    if (!s.isEmpty() && !s.startsWith('#'))
                        argCopy += s.split(' ');
                }
            }
            if (!rcfile.isEmpty()) {
                rc = rcfile.readAll();
                if (!rc.isEmpty()) {
                    for (const String& s : rc.split('\n')) {
                        if (!s.isEmpty() && !s.startsWith('#'))
                            argCopy += s.split(' ');
                    }
                }
            }
            const int s = argCopy.size();
            for (int i=0; i<s; ++i) {
                String &arg = argCopy.at(i);
                if (!arg.isEmpty())
                    argList.append(arg.data());
            }
        }

        for (int i=1; i<argc; ++i)
            argList.append(originalArgv[i]);

        optind = 1;
    }

    Server::Options serverOpts;
    serverOpts.threadStackSize = defaultStackSize;
    serverOpts.socketFile = String::format<128>("%s.rdm", Path::home().constData());
    serverOpts.jobCount = std::max(2, ThreadPool::idealThreadCount());
    serverOpts.headerErrorJobCount = -1;
    serverOpts.rpVisitFileTimeout = DEFAULT_RP_VISITFILE_TIMEOUT;
    serverOpts.rpIndexDataMessageTimeout = DEFAULT_RP_INDEXER_MESSAGE_TIMEOUT;
    serverOpts.rpConnectTimeout = DEFAULT_RP_CONNECT_TIMEOUT;
    serverOpts.rpConnectAttempts = DEFAULT_RP_CONNECT_ATTEMPTS;
    serverOpts.maxFileMapScopeCacheSize = DEFAULT_RDM_MAX_FILE_MAP_CACHE_SIZE;
    serverOpts.rpNiceValue = INT_MIN;
    serverOpts.options = Server::Wall|Server::SpellChecking;
    serverOpts.maxCrashCount = DEFAULT_MAX_CRASH_COUNT;
    serverOpts.completionCacheSize = DEFAULT_COMPLETION_CACHE_SIZE;
    serverOpts.rp = defaultRP();
    strcpy(crashDumpFilePath, "crash.dump");
#ifdef OS_FreeBSD
    serverOpts.options |= Server::NoFileManagerWatch;
#endif
// #ifndef NDEBUG
//     serverOpts.options |= Server::SuspendRPOnCrash;
// #endif
    serverOpts.dataDir = String::format<128>("%s.rtags", Path::home().constData());

    const char *logFile = 0;
    Flags<LogFlag> logFlags = DontRotate|LogStderr;
    LogLevel logLevel(LogLevel::Error);
    LogLevel logFileLogLevel(LogLevel::Error);
    bool sigHandler = true;
    assert(Path::home().endsWith('/'));
    int argCount = argList.size();
    char **args = argList.data();
    bool defaultDataDir = true;
    int inactivityTimeout = 0;

    while (true) {
        const int c = getopt_long(argCount, args, shortOptions.constData(), opts, 0);
        if (c == -1)
            break;
        switch (c) {
        case 'N':
        case 'c':
            // ignored
            break;
        case 'S':
            logLevel = LogLevel::None;
            break;
        case 'X':
            serverOpts.excludeFilters += String(optarg).split(';');
            break;
        case 'G':
            serverOpts.blockedArguments << optarg;
            break;
        case 1:
            serverOpts.options |= Server::NoComments;
            break;
        case 10:
            serverOpts.options |= Server::WatchSourcesOnly;
            break;
        case 11:
            if (!strcmp(optarg, "clear") || !strcmp(optarg, "none")) {
                serverOpts.debugLocations.clear();
            } else {
                serverOpts.debugLocations << optarg;
            }
            break;
        case 12:
            serverOpts.tcpPort = atoi(optarg);
            if (!serverOpts.tcpPort) {
                fprintf(stderr, "Invalid port %s for --tcp-port\n", optarg);
                return 1;
            }
            break;
        case 13:
            serverOpts.options |= Server::NoFileLock;
            break;
        case 14:
            serverOpts.options |= Server::PCHEnabled;
            break;
        case 15:
            serverOpts.options |= Server::NoFileManager;
            break;
        case 16:
            serverOpts.options |= Server::ValidateFileMaps;
            break;
        case 17:
            serverOpts.rp = optarg;
            if (serverOpts.rp.isFile())
                serverOpts.rp.resolve();
            break;
        case 18:
            logFlags |= LogTimeStamp;
            break;
        case 19:
            strcpy(crashDumpFilePath, optarg);
            break;
        case 20:
            serverOpts.root = optarg;
            if (!serverOpts.root.resolve() || !serverOpts.root.isDir()) {
                fprintf(stderr, "%s is not a directory\n", optarg);
                return 1;
            }
            break;
        case 2:
            fprintf(stdout, "%s\n", RTags::versionString().constData());
            return 0;
        case 6:
            daemon = true;
            logLevel = LogLevel::None;
            break;
        case 9:
            if (!strcasecmp(optarg, "verbose-debug")) {
                logFileLogLevel = LogLevel::VerboseDebug;
            } else if (!strcasecmp(optarg, "debug")) {
                logFileLogLevel = LogLevel::Debug;
            } else if (!strcasecmp(optarg, "warning")) {
                logFileLogLevel = LogLevel::Warning;
            } else if (!strcasecmp(optarg, "error")) {
                logFileLogLevel = LogLevel::Error;
            } else {
                fprintf(stderr, "Unknown log level: %s options are error, warning, debug or verbose-debug\n",
                        optarg);
                return 1;
            }
            break;
        case 'U':
            serverOpts.extraCompilers.append(std::regex(optarg));
            break;
        case 'E':
            serverOpts.options |= Server::SeparateDebugAndRelease;
            break;
        case 'g':
            serverOpts.options |= Server::EnableNDEBUG;
            break;
        case 'Q':
            serverOpts.options |= Server::StartSuspended;
            break;
        case 'Z':
            serverOpts.rpVisitFileTimeout = atoi(optarg);
            if (serverOpts.rpVisitFileTimeout < 0) {
                fprintf(stderr, "Invalid argument to -Z %s\n", optarg);
                return 1;
            }
            if (!serverOpts.rpVisitFileTimeout)
                serverOpts.rpVisitFileTimeout = -1;
            break;
        case 'y':
            serverOpts.maxFileMapScopeCacheSize = atoi(optarg);
            if (serverOpts.maxFileMapScopeCacheSize <= 0) {
                fprintf(stderr, "Invalid argument to -y %s\n", optarg);
                return 1;
            }
            break;
        case 'O':
            serverOpts.rpConnectTimeout = atoi(optarg);
            if (serverOpts.rpConnectTimeout < 0) {
                fprintf(stderr, "Invalid argument to -O %s\n", optarg);
                return 1;
            }
            break;
        case 3:
            serverOpts.rpConnectAttempts = atoi(optarg);
            if (serverOpts.rpConnectAttempts <= 0) {
                fprintf(stderr, "Invalid argument to --rp-connect-attempts %s\n", optarg);
                return 1;
            }
            break;
        case 'k':
            serverOpts.threadStackSize = atoi(optarg);
            if (serverOpts.threadStackSize < 0) {
                fprintf(stderr, "Invalid argument to -k %s\n", optarg);
                return 1;
            }
            break;
        case 'b':
            serverOpts.ignoredCompilers.insert(Path::resolved(optarg));
            break;
        case 't': {
            Path test(optarg);
            if (!test.resolve() || !test.isFile()) {
                fprintf(stderr, "%s doesn't seem to be a file\n", optarg);
                return 1;
            }
            serverOpts.tests += test;
            break; }
        case 'z':
            serverOpts.testTimeout = atoi(optarg);
            if (serverOpts.testTimeout <= 0) {
                fprintf(stderr, "Invalid argument to -z %s\n", optarg);
                return 1;
            }
            break;
        case 'n':
            serverOpts.socketFile = optarg;
            break;
        case 'd':
            defaultDataDir = false;
            serverOpts.dataDir = String::format<128>("%s", Path::resolved(optarg).constData());
            break;
        case 'h':
            usage(stdout);
            return 0;
        case 'Y':
            serverOpts.options |= Server::NoNoUnknownWarningsOption;
            break;
        case 'p':
            serverOpts.options |= Server::Progress;
            break;
        case 'R':
            serverOpts.options |= Server::EnableCompilerManager;
            break;
        case 'm':
            serverOpts.options |= Server::DisallowMultipleSources;
            break;
        case 'o':
            serverOpts.options |= Server::NoStartupCurrentProject;
            break;
        case 'w':
            serverOpts.options |= Server::WatchSystemPaths;
            break;
        case 'q':
            serverOpts.options |= Server::SuspendRPOnCrash;
            break;
        case 'M':
#ifdef OS_FreeBSD
            serverOpts.options &= ~Server::NoFileManagerWatch;
#else
            serverOpts.options |= Server::NoFileManagerWatch;
#endif
            break;
        case 'B':
            serverOpts.options |= Server::NoFileSystemWatch;
            break;
        case 'V':
            serverOpts.argTransform = Process::findCommand(optarg);
            if (strlen(optarg) && serverOpts.argTransform.isEmpty()) {
                fprintf(stderr, "Invalid argument to -V. Can't resolve %s", optarg);
                return 1;
            }

            break;
      case 'F':
            serverOpts.options |= Server::IgnorePrintfFixits;
            break;
        case 'f':
            serverOpts.options |= Server::NoUnlimitedErrors;
            break;
        case 'l':
            serverOpts.options &= ~Server::SpellChecking;
            break;
        case 'W':
            serverOpts.options &= ~Server::Wall;
            break;
        case 'u':
            serverOpts.options |= Server::Weverything;
            break;
        case 'P':
            serverOpts.options |= Server::AllowPedantic;
            break;
        case 'C':
            serverOpts.options |= Server::ClearProjects;
            break;
        case 'e':
            putenv(optarg);
            break;
        case 'x':
            sigHandler = false;
            break;
        case 'K':
            serverOpts.maxCrashCount = atoi(optarg);
            if (serverOpts.maxCrashCount <= 0) {
                fprintf(stderr, "Invalid argument to -K %s\n", optarg);
                return 1;
            }
            break;
        case 'i':
            serverOpts.completionCacheSize = atoi(optarg);
            if (serverOpts.completionCacheSize <= 0) {
                fprintf(stderr, "Invalid argument to -i %s\n", optarg);
                return 1;
            }
            break;
        case 'T':
            serverOpts.rpIndexDataMessageTimeout = atoi(optarg);
            if (serverOpts.rpIndexDataMessageTimeout <= 0) {
                fprintf(stderr, "Can't parse argument to -T %s.\n", optarg);
                return 1;
            }
            break;
        case 'a': {
            bool ok;
            serverOpts.rpNiceValue = String(optarg).toLong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -a %s.\n", optarg);
                return 1;
            }
            break; }
        case 'j': {
            bool ok;
            serverOpts.jobCount = String(optarg).toULong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -j %s. -j must be a positive integer.\n", optarg);
                return 1;
            }
            break; }
        case 'H': {
            bool ok;
            serverOpts.headerErrorJobCount = String(optarg).toULong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -H %s. -H must be a positive integer.\n", optarg);
                return 1;
            }
            break; }
        case 'r': {
            int large = atoi(optarg);
            if (large <= 0) {
                fprintf(stderr, "Can't parse argument to -r %s\n", optarg);
                return 1;
            }
            serverOpts.defaultArguments.append("-Wlarge-by-value-copy=" + String(optarg)); // ### not quite working
            break; }
        case 'D': {
            const char *eq = strchr(optarg, '=');
            Source::Define def;
            if (!eq) {
                def.define = optarg;
            } else {
                def.define = String(optarg, eq - optarg);
                def.value = eq + 1;
            }
            serverOpts.defines.append(def);
            break; }
        case 'I':
            serverOpts.includePaths.append(Source::Include(Source::Include::Type_Include, Path::resolved(optarg)));
            break;
        case 's':
            serverOpts.includePaths.append(Source::Include(Source::Include::Type_System, Path::resolved(optarg)));
            break;
        case 'L':
            logFile = optarg;
            logLevel = LogLevel::None;
            break;
        case 'v':
            if (logLevel != LogLevel::None)
                ++logLevel;
            break;
#ifdef RTAGS_HAS_LAUNCHD
        case 4:
            serverOpts.options |= Server::Launchd;
            break;
#endif
        case 5:
            inactivityTimeout = atoi(optarg); // seconds.
            if (inactivityTimeout <= 0) {
                fprintf(stderr, "Invalid argument to --inactivity-timeout %s\n", optarg);
                return 1;
            }
            break;
        case 7:
            serverOpts.options |= Server::RPLogToSyslog;
            break;
        case 8:
            serverOpts.options |= Server::CompletionsNoFilter;
            break;
        case '?': {
            fprintf(stderr, "Run rdm --help for help\n");
            return 1; }
        }
    }
    if (optind < argCount) {
        fprintf(stderr, "rdm: unexpected option -- '%s'\n", args[optind]);
        return 1;
    }

    if (daemon) {
        switch (fork()) {
        case -1:
            fprintf(stderr, "Failed to fork (%d) %s\n", errno, strerror(errno));
            return 1;
        case 0:
            setsid();
            switch (fork()) {
            case -1:
                fprintf(stderr, "Failed to fork (%d) %s\n", errno, strerror(errno));
                return 1;
            case 0:
                break;
            default:
                return 0;
            }
            break;
        default:
            return 0;
        }
    }

    if (serverOpts.excludeFilters.isEmpty())
        serverOpts.excludeFilters = String(EXCLUDEFILTER_DEFAULT).split(';');

    if (!serverOpts.headerErrorJobCount) {
        serverOpts.headerErrorJobCount = std::max<size_t>(1, serverOpts.jobCount / 2);
    } else {
        serverOpts.headerErrorJobCount = std::min(serverOpts.headerErrorJobCount, serverOpts.jobCount);
    }

    if (sigHandler) {
        signal(SIGSEGV, signalHandler);
        signal(SIGBUS, signalHandler);
        signal(SIGILL, signalHandler);
        signal(SIGABRT, signalHandler);
    }

    // Shell-expand logFile
    Path logPath(logFile); logPath.resolve();

    if (!initLogging(argv[0], logFlags, logLevel, logPath.constData(), logFileLogLevel)) {
        fprintf(stderr, "Can't initialize logging with %d %s %s\n",
                logLevel.toInt(), logFile ? logFile : "", logFlags.toString().constData());
        return 1;
    }

#ifdef RTAGS_HAS_LAUNCHD
    if (serverOpts.options & Server::Launchd) {
        // Clamp inactivity timeout. launchd starts to worry if the
        // process runs for less than 10 seconds.

        static const int MIN_INACTIVITY_TIMEOUT = 15; // includes
                                                      // fudge factor.

        if (inactivityTimeout < MIN_INACTIVITY_TIMEOUT) {
            inactivityTimeout = MIN_INACTIVITY_TIMEOUT;
            fprintf(stderr, "launchd mode - clamped inactivity timeout to %d to avoid launchd warnings.\n", inactivityTimeout);
        }
    }
#endif

    EventLoop::SharedPtr loop(new EventLoop);
    loop->init(EventLoop::MainEventLoop|EventLoop::EnableSigIntHandler|EventLoop::EnableSigTermHandler);

    std::shared_ptr<Server> server(new Server);
    if (!serverOpts.tests.isEmpty()) {
        char buf[1024];
        Path path;
        while (true) {
            strcpy(buf, "/tmp/rtags-test-XXXXXX");
            if (!mkdtemp(buf)) {
                fprintf(stderr, "Failed to mkdtemp (%d)\n", errno);
                return 1;
            }
            path = buf;
            path.resolve();
            break;
        }
        serverOpts.dataDir = path;
        strcpy(buf, "/tmp/rtags-sock-XXXXXX");
        const int fd = mkstemp(buf);
        if (fd == -1) {
            fprintf(stderr, "Failed to mkstemp (%d)\n", errno);
            return 1;
        }
        close(fd);
        serverOpts.socketFile = buf;
        serverOpts.socketFile.resolve();
    }
    if (defaultDataDir) {
        Path migration = String::format<128>("%s.rtags-file", Path::home().constData());
        if (migration.isDir()) {
            Rct::removeDirectory(serverOpts.dataDir);
            rename(migration.constData(), serverOpts.dataDir.constData());
            error() << "Migrated datadir from ~/.rtags-file ~/.rtags";
        }
    }
    serverOpts.dataDir = serverOpts.dataDir.ensureTrailingSlash();

#ifdef HAVE_BACKTRACE
    if (strlen(crashDumpFilePath)) {
        if (crashDumpFilePath[0] != '/') {
            const String f = crashDumpFilePath;
            snprintf(crashDumpFilePath, sizeof(crashDumpFilePath), "%s%s", serverOpts.dataDir.constData(), f.constData());
        }
        snprintf(crashDumpTempFilePath, sizeof(crashDumpTempFilePath), "%s.tmp", crashDumpFilePath);
        Path::mkdir(serverOpts.dataDir);
        crashDumpFile = fopen(crashDumpTempFilePath, "w");
        if (!crashDumpFile) {
            fprintf(stderr, "Couldn't open temp file %s for write (%d)", crashDumpTempFilePath, errno);
            return 1;
        }
    }
#endif

    if (!server->init(serverOpts)) {
        cleanupLogging();
        return 1;
    }

    if (!serverOpts.tests.isEmpty()) {
        return server->runTests() ? 0 : 1;
    }

    loop->setInactivityTimeout(inactivityTimeout * 1000);

    loop->exec();
    const int ret = server->exitCode();
    server.reset();
    cleanupLogging();
    return ret;
}
Example #4
0
Value CL_symbol_macrolet(Value args, Environment * env, Thread * thread)
{
  Value varlist = check_list(car(args));
  Value result = NIL;
  void * last_special_binding = thread->last_special_binding();
  Environment * ext = new Environment(env);

  if (varlist != NIL)
    {
      for (unsigned long i = length(varlist); i-- > 0;)
        {
          Value obj = car(varlist);
          varlist = xcdr(varlist);
          if (consp(obj) && length(obj) == 2)
            {
              Value name = xcar(obj);
              Symbol * sym = check_symbol(name);
              if (sym->is_special_variable() || env->is_declared_special(name))
                {
                  String * s = new String("Attempt to bind the special variable ");
                  s->append(::prin1_to_string(name));
                  s->append(" with SYMBOL-MACROLET.");
                  return signal_lisp_error(new ProgramError(s));
                }
              ext->bind(name, make_value(new SymbolMacro(xcar(xcdr(obj)))));
            }
          else
            {
              String * s = new String("Malformed symbol-expansion pair in SYMBOL-MACROLET: ");
              s->append(::prin1_to_string(obj));
              return signal_lisp_error(new ProgramError(s));
            }
        }
    }

  Value body = xcdr(args);

  // Process declarations.
  Value specials = NIL;
  while (body != NIL)
    {
      Value obj = car(body);
      if (consp(obj) && xcar(obj) == S_declare)
        {
          Value decls = xcdr(obj);
          while (decls != NIL)
            {
              Value decl = car(decls);
              if (consp(decl) && xcar(decl) == S_special)
                {
                  Value vars = xcdr(decl);
                  while (vars != NIL)
                    {
                      Value name = car(vars);

                      // "If declaration contains a special declaration that
                      // names one of the symbols being bound by SYMBOL-MACROLET,
                      // an error of type PROGRAM-ERROR is signaled."
                      Value list = xcar(args);
                      while (list != NIL)
                        {
                          if (xcar(xcar(list)) == name)
                            {
                              String * s = new String(::prin1_to_string(name));
                              s->append(" is a symbol-macro and thus can't be declared special.");
                              return signal_lisp_error(new ProgramError(s));
                            }
                          list = xcdr(list);
                        }

                      specials = make_cons(name, specials);
                      vars = xcdr(vars);
                    }
                }
              decls = xcdr(decls);
            }
          body = xcdr(body);
        }
      else
        break;
    }
  while (specials != NIL)
    {
      ext->declare_special(xcar(specials));
      specials = xcdr(specials);
    }

  while (body != NIL)
    {
      result = eval(car(body), ext, thread);
      body = xcdr(body);
    }
  thread->set_last_special_binding(last_special_binding);
  return result;
}
Example #5
0
P<BundleData> DirBundleLoader::loadBundle(String location)
{
	P<BundleData> bundleData = new BundleData();

	bundleData->setLocation(location);

	String path = location;
	path.append(L"\\META-INF\\MANIFEST.MF");
	P<File> file = new File(path);

	P<Manifest> mf = new Manifest(file);
	P<Map<String,String>> entries = mf->getEntries();

	String symbolicName = entries->get(Constants::BUNDLE_SYMBOLICNAME);
	if (symbolicName == (String)null || symbolicName.equals(L"") ) 
	{
        throw BundleException(String(L"Bundle symbolic name not found: ") + file->getAbsolutePath());
    }

	//if (framework->getBundle(symbolicName) != null) 
	//{
 //       throw BundleException(String(L"Bundle(SymbolicName: ") + symbolicName + String(L") already exists: ") + file->getAbsolutePath());
 //   }

	bundleData->setSymbolicName(symbolicName);

	//get Bundle-Name
	String name = entries->get(Constants::BUNDLE_NAME);
    if (name == (String)null || name.equals(L"")) 
	{
		name = File(location).getName();
    }

	bundleData->setName(name);

    // Validate the bundle activator.

	String activator = entries->get(Constants::BUNDLE_ACTIVATOR);
    if (activator == (String)null || symbolicName.equals(L"") )
	{
        throw BundleException(String(L"Bundle activator definition not found: ") + file->getAbsolutePath());
    }

	bundleData->setActivator(activator);

	String nativeLib = entries->get(Constants::BUNDLE_NATIVE_LIB);
	if (nativeLib == (String)null || nativeLib.equals(L"") )
	{
		nativeLib = name + String(L".dll");
	}

	nativeLib = String(location) + String(L"\\") + nativeLib;

	bundleData->setNativeLib(nativeLib);

	//P<Library> lib= new DllLibrary();
	//lib->load(this->nativeLib);

	//if (!lib->containsClass(activator)) 
	//{
 //       throw BundleException(String(L"Bundle activator class(\"") + activator + String(L"\") not found: ") + file->getAbsolutePath());
 //   }

	//lib->free();

	String description = entries->get(Constants::BUNDLE_DESCRIPTION);
    if (description == (String)null || description.equals(L"")) 
	{
        description = L"";
    }

	bundleData->setDescription(description);


	// Parse classpaths
    String classpath = entries->get(Constants::BUNDLE_CLASSPATH);

	P<Array<String>> classPaths = null;

    if (classpath != null) 
	{
        Array<String> theClassPaths =classpath.split(L",");

		int size = theClassPaths.size();
		classPaths = new Array<String>(size);

        for (int i = 0; i < size; i++) 
		{
			String theClassPath =theClassPaths.get(i);

			// Check the classpath entry
			bool entryExists = false;
			
			String theRealPath = generateURL(location, theClassPath);
			File theFile(theRealPath);

			entryExists = theFile.exists();

			if (entryExists) 
			{
				classPaths->set(i, theFile.getCanonicalPath());
			}
			else 
			{
				throw BundleException(String(L"Classpath(\"") + theClassPath + String(L"\") not found: ") + file->getAbsolutePath());
			}
		}
    }
	else 
	{
		classPaths = new Array<String>();
	}

	bundleData->setClassPaths(classPaths);

	// Parse export packages
	String exportPackages = entries->get(Constants::EXPORT_PACKAGE);
	Array<String> exportedPackages;

    if (exportPackages != null) 
	{
         
        exportedPackages =exportPackages.split(L",");
    }
	else 
	{
		exportedPackages = Array<String>();
	}

	bundleData->setExportedPackages(new Array<String>(exportedPackages));

	// Parse import packages, nee
	String importpackages = entries->get(Constants::IMPORT_PACKAGE);
	Array<String> importedPackages;

    if (importpackages != null)
	{
		importedPackages =importpackages.split(L",");
    }
	else 
	{
        importedPackages = Array<String>();
    }

	bundleData->setImportedPackages(new Array<String>(importedPackages));

	// Parse reuqired extensions
	String requiredbundles = entries->get(Constants::REQUIRE_BUNDLE);
	Array<String> requiredBundles;

    if (requiredbundles != null) 
	{
		requiredBundles =requiredbundles.split(L",");
    }
	else 
	{
        requiredBundles =  Array<String>();
    }

	bundleData->setRequiredBundles(new Array<String>(requiredBundles));

	return bundleData;
}
String IndicationFormatter::_formatDefaultIndicationText(
    const CIMInstance & indication,
    const ContentLanguages & contentLangs)
{
    PEG_METHOD_ENTER (TRC_IND_FORMATTER,
        "IndicationFormatter::_formatDefaultIndicationText");

    CIMInstance indicationInstance = indication.clone();
    String propertyName;
    String indicationStr;
    Uint32 propertyCount = indicationInstance.getPropertyCount();

    indicationStr.append("Indication (default format):");

    Boolean canLocalize = false;

#if defined(PEGASUS_HAS_ICU) && defined(PEGASUS_INDFORMATTER_USE_ICU)
    Locale locale;
    canLocalize = _canLocalize(contentLangs, locale);
#endif

    for (Uint32 i=0; i < propertyCount; i++)
    {
        CIMProperty property = indicationInstance.getProperty(i);
        propertyName = property.getName().getString();
        CIMValue propertyValue = property.getValue();
        Boolean valueIsNull = propertyValue.isNull();
        Boolean isArray = propertyValue.isArray();

        indicationStr.append(propertyName);
        indicationStr.append(" = ");

	CIMType type = propertyValue.getType();

        if (!valueIsNull)
        {
            if (isArray)
            {
		indicationStr.append(_getArrayValues(propertyValue, "",
		    contentLangs));
            }
            else // value is not an array
            {
#if defined(PEGASUS_HAS_ICU) && defined(PEGASUS_INDFORMATTER_USE_ICU)
		if (canLocalize)
		{
		    if (type == CIMTYPE_DATETIME)
		    {
			CIMDateTime dateTimeValue;
			propertyValue.get(dateTimeValue);
		        indicationStr.append(_localizeDateTime(dateTimeValue,
		    	    locale));
		    }
		    else if (type == CIMTYPE_BOOLEAN)
		    {
			Boolean booleanValue;
			propertyValue.get(booleanValue);
		        indicationStr.append(_localizeBooleanStr(booleanValue,
		    	    locale));
		    }
		    else
		    {
			indicationStr.append(propertyValue.toString());
		    }
		}
		else
		{
		    if (type == CIMTYPE_BOOLEAN)
		    {
                        indicationStr.append(_getBooleanStr(propertyValue));
		    }
		    else
		    {
                        indicationStr.append(propertyValue.toString());
		    }
		}
#else
		if (type == CIMTYPE_BOOLEAN)
		{
                    indicationStr.append(_getBooleanStr(propertyValue));
		}
		else
		{
                    indicationStr.append(propertyValue.toString());
		}
#endif
            }
        }
	else
	{
	    indicationStr.append("NULL");
	}

        if (i < propertyCount -1)
        {
            indicationStr.append(", ");
        }

        propertyName.clear();
    }

    PEG_METHOD_EXIT();

    return (indicationStr);
}
Example #7
0
		String File::absolutePath(const String &filePath)
		{
			String path = normalizePath(filePath);
			if(path.isEmpty())
				return String();
				
			String base;
			unsigned int start;
#if WITCHENGINE_PLATFORM == WITCHENGINE_PLATFORM_WIN32 || WITCHENGINE_PLATFORM == WITCHENGINE_PLATFORM_WIN64
			if(path.match("?:*"))
				start = 1;
			else if(path.match("\\\\*"))
			{
				base = "\\\\";
				start = 2;
			}
			else if(path.startsWith('\\'))
			{
				String drive = Directory::current().substrTo('\\');
				String end = path.substr(1, -1);
				if(end.isEmpty())
					path = drive;
				else
					path = drive + '\\' + end;
					
				start = 1;
			}
			else
			{
				// Throw an exception.
				return path;
			}
#else
			base = '';
			start = 0;
#endif

			static String upDir = WITCH_DIRECTORY_SEPARATOR + String('.');
			
			if(path.find(upDir) == String::npos)
				return path;
				
			std::vector<String> sep;
			if(path.split(sep, WITCH_DIRECTORY_SEPARATOR) <= 1)
				return path;
				
			unsigned int pathLen = base.size();
			for(unsigned int i = 0; i < sep.size(); ++i)
			{
				if(sep[i] == '.')
					sep.erase(sep.begin() + i--);
				else if(sep[i] == "..")
				{
					if(i > start)
						sep.erase(sep.begin() - i--);
						
					sep.erase(sep.begin() + i--);
				}
				else
					pathLen += sep[i].size();
			}
			
			pathLen += sep.size() - 1;
			
			String stream;
			stream.reserve(pathLen);
			stream.append(base);
			for(unsigned int i = 0; i < sep.size(); ++i)
			{
				stream.append(sep[i]);
				if(i != sep.size() - 1)
					stream.append(WITCH_DIRECTORY_SEPARATOR);
			}
			
			return stream;
		}
Example #8
0
 static PassRefPtr<SharedBuffer> readFile(const char* fileName)
 {
     String filePath = testing::blinkRootDir();
     filePath.append(fileName);
     return testing::readFromFile(filePath);
 }
String CSSPrimitiveValue::cssText() const
{
    // FIXME: return the original value instead of a generated one (e.g. color
    // name if it was specified) - check what spec says about this

    if (m_hasCachedCSSText) {
        ASSERT(cssTextCache().contains(this));
        return cssTextCache().get(this);
    }

    String text;
    switch (m_type) {
        case CSS_UNKNOWN:
            // FIXME
            break;
        case CSS_NUMBER:
        case CSS_PARSER_INTEGER:
            text = formatNumber(m_value.num);
            break;
        case CSS_PERCENTAGE:
            text = formatNumber(m_value.num) + "%";
            break;
        case CSS_EMS:
            text = formatNumber(m_value.num) + "em";
            break;
        case CSS_EXS:
            text = formatNumber(m_value.num) + "ex";
            break;
        case CSS_REMS:
            text = formatNumber(m_value.num) + "rem";
            break;
        case CSS_PX:
            text = formatNumber(m_value.num) + "px";
            break;
        case CSS_CM:
            text = formatNumber(m_value.num) + "cm";
            break;
        case CSS_MM:
            text = formatNumber(m_value.num) + "mm";
            break;
        case CSS_IN:
            text = formatNumber(m_value.num) + "in";
            break;
        case CSS_PT:
            text = formatNumber(m_value.num) + "pt";
            break;
        case CSS_PC:
            text = formatNumber(m_value.num) + "pc";
            break;
        case CSS_DEG:
            text = formatNumber(m_value.num) + "deg";
            break;
        case CSS_RAD:
            text = formatNumber(m_value.num) + "rad";
            break;
        case CSS_GRAD:
            text = formatNumber(m_value.num) + "grad";
            break;
        case CSS_MS:
            text = formatNumber(m_value.num) + "ms";
            break;
        case CSS_S:
            text = formatNumber(m_value.num) + "s";
            break;
        case CSS_HZ:
            text = formatNumber(m_value.num) + "hz";
            break;
        case CSS_KHZ:
            text = formatNumber(m_value.num) + "khz";
            break;
        case CSS_TURN:
            text = formatNumber(m_value.num) + "turn";
            break;
        case CSS_DIMENSION:
            // FIXME
            break;
        case CSS_STRING:
            text = quoteCSSStringIfNeeded(m_value.string);
            break;
        case CSS_URI:
            text = "url(" + quoteCSSURLIfNeeded(m_value.string) + ")";
            break;
        case CSS_IDENT:
            text = valueOrPropertyName(m_value.ident);
            break;
        case CSS_ATTR: {
            DEFINE_STATIC_LOCAL(const String, attrParen, ("attr("));

            Vector<UChar> result;
            result.reserveInitialCapacity(6 + m_value.string->length());

            append(result, attrParen);
            append(result, m_value.string);
            result.uncheckedAppend(')');

            text = String::adopt(result);
            break;
        }
        case CSS_COUNTER:
            text = "counter(";
            text += String::number(m_value.num);
            text += ")";
            // FIXME: Add list-style and separator
            break;
        case CSS_RECT: {
            DEFINE_STATIC_LOCAL(const String, rectParen, ("rect("));

            Rect* rectVal = getRectValue();
            Vector<UChar> result;
            result.reserveInitialCapacity(32);
            append(result, rectParen);

            append(result, rectVal->top()->cssText());
            result.append(' ');

            append(result, rectVal->right()->cssText());
            result.append(' ');

            append(result, rectVal->bottom()->cssText());
            result.append(' ');

            append(result, rectVal->left()->cssText());
            result.append(')');

            text = String::adopt(result);
            break;
        }
        case CSS_RGBCOLOR:
        case CSS_PARSER_HEXCOLOR: {
            DEFINE_STATIC_LOCAL(const String, commaSpace, (", "));
            DEFINE_STATIC_LOCAL(const String, rgbParen, ("rgb("));
            DEFINE_STATIC_LOCAL(const String, rgbaParen, ("rgba("));

            RGBA32 rgbColor = m_value.rgbcolor;
            if (m_type == CSS_PARSER_HEXCOLOR)
                Color::parseHexColor(m_value.string, rgbColor);
            Color color(rgbColor);

            Vector<UChar> result;
            result.reserveInitialCapacity(32);
            if (color.hasAlpha())
                append(result, rgbaParen);
            else
                append(result, rgbParen);

            appendNumber(result, static_cast<unsigned char>(color.red()));
            append(result, commaSpace);

            appendNumber(result, static_cast<unsigned char>(color.green()));
            append(result, commaSpace);

            appendNumber(result, static_cast<unsigned char>(color.blue()));
            if (color.hasAlpha()) {
                append(result, commaSpace);
                append(result, String::number(color.alpha() / 256.0f));
            }

            result.append(')');
            text = String::adopt(result);
            break;
        }
        case CSS_PAIR:
            text = m_value.pair->first()->cssText();
            text += " ";
            text += m_value.pair->second()->cssText();
            break;
#if ENABLE(DASHBOARD_SUPPORT)
        case CSS_DASHBOARD_REGION:
            for (DashboardRegion* region = getDashboardRegionValue(); region; region = region->m_next.get()) {
                if (!text.isEmpty())
                    text.append(' ');
                text += "dashboard-region(";
                text += region->m_label;
                if (region->m_isCircle)
                    text += " circle";
                else if (region->m_isRectangle)
                    text += " rectangle";
                else
                    break;
                if (region->top()->m_type == CSS_IDENT && region->top()->getIdent() == CSSValueInvalid) {
                    ASSERT(region->right()->m_type == CSS_IDENT);
                    ASSERT(region->bottom()->m_type == CSS_IDENT);
                    ASSERT(region->left()->m_type == CSS_IDENT);
                    ASSERT(region->right()->getIdent() == CSSValueInvalid);
                    ASSERT(region->bottom()->getIdent() == CSSValueInvalid);
                    ASSERT(region->left()->getIdent() == CSSValueInvalid);
                } else {
                    text.append(' ');
                    text += region->top()->cssText() + " ";
                    text += region->right()->cssText() + " ";
                    text += region->bottom()->cssText() + " ";
                    text += region->left()->cssText();
                }
                text += ")";
            }
            break;
#endif
        case CSS_PARSER_OPERATOR: {
            char c = static_cast<char>(m_value.ident);
            text = String(&c, 1U);
            break;
        }
        case CSS_PARSER_IDENTIFIER:
            text = quoteCSSStringIfNeeded(m_value.string);
            break;
    }

    ASSERT(!cssTextCache().contains(this));
    cssTextCache().set(this, text);
    m_hasCachedCSSText = true;
    return text;
}
Example #10
0
/**
    ATTN-RK: The DMTF specification for the string form of an
    object path makes it impossible for a parser to distinguish
    between a key values of String type and Reference type.

    Given the ambiguity, this implementation takes a guess at the
    type of a quoted key value.  If the value can be parsed into
    a CIMObjectPath with at least one key binding, the type is
    set to REFERENCE.  Otherwise, the type is set to STRING.
    Note: This algorithm appears to be in line with what the Sun
    WBEM Services implementation does.

    To be totally correct, it would be necessary to retrieve the
    class definition and look up the types of the key properties
    to determine how to interpret the key values.  This is clearly
    too inefficient for internal transformations between
    CIMObjectPaths and String values.
*/
void _parseKeyBindingPairs(
    const String& objectName,
    char*& p,
    Array<CIMKeyBinding>& keyBindings)
{
    // Get the key-value pairs:

    while (*p)
    {
        // Get key part:

        char* equalsign = strchr(p, '=');
        if (!equalsign)
        {
            throw MalformedObjectNameException(objectName);
        }

        *equalsign = 0;

        if (!CIMName::legal(p))
            throw MalformedObjectNameException(objectName);

        CIMName keyName (p);

        // Get the value part:

        String valueString;
        p = equalsign + 1;
        CIMKeyBinding::Type type;

        if (*p == '"')
        {
            // Could be CIMKeyBinding::STRING or CIMKeyBinding::REFERENCE

            p++;

            while (*p && *p != '"')
            {
                if (*p == '\\')
                {
                    *p++;

                    if ((*p != '\\') && (*p != '"'))
                    {
                        throw MalformedObjectNameException(objectName);
                    }
                }

                valueString.append(*p++);
            }

            if (*p++ != '"')
                throw MalformedObjectNameException(objectName);

            /*
                Guess at the type of this quoted key value.  If the value
                can be parsed into a CIMObjectPath with at least one key
                binding, the type is assumed to be a REFERENCE.  Otherwise,
                the type is set to STRING.  (See method header for details.)
             */
            type = CIMKeyBinding::STRING;

            try
            {
                CIMObjectPath testForPath(valueString);
                if (testForPath.getKeyBindings().size() > 0)
                {
                    // We've found a reference value!
                    type = CIMKeyBinding::REFERENCE;
                }
            }
            catch (const Exception &)
            {
                // Not a reference value; leave type as STRING
            }
        }
        else if (toupper(*p) == 'T' || toupper(*p) == 'F')
        {
            type = CIMKeyBinding::BOOLEAN;

            char* r = p;
            Uint32 n = 0;

            while (*r && *r != ',')
            {
                *r = toupper(*r);
                r++;
                n++;
            }

            if (!(((strncmp(p, "TRUE", n) == 0) && n == 4) ||
                  ((strncmp(p, "FALSE", n) == 0) && n == 5)))
                throw MalformedObjectNameException(objectName);

            valueString.assign(p, n);

            p = p + n;
        }
        else
        {
            type = CIMKeyBinding::NUMERIC;

            char* r = p;
            Uint32 n = 0;

            while (*r && *r != ',')
            {
                r++;
                n++;
            }

            Boolean isComma = false;
            if (*r)
            {
                *r = '\0';
                isComma = true;
            }

            Sint64 x;

            if (!XmlReader::stringToSignedInteger(p, x))
                throw MalformedObjectNameException(objectName);

            valueString.assign(p, n);

            if (isComma)
            {
                *r = ',';
            }

            p = p + n;
        }

        keyBindings.append(CIMKeyBinding(keyName.getString (), valueString,
            type));

        if (*p)
        {
            if (*p++ != ',')
            {
                throw MalformedObjectNameException(objectName);
            }
        }
    }

    _BubbleSort(keyBindings);
}
bool ResourceHandle::start(NetworkingContext* context)
{
    if (firstRequest().url().isLocalFile() || firstRequest().url().protocolIsData()) {
        ref(); // balanced by deref in fileLoadTimer
        if (d->m_loadSynchronously)
            fileLoadTimer(0);
        else
            d->m_fileLoadTimer.startOneShot(0.0);
        return true;
    }

    if (!d->m_internetHandle)
        d->m_internetHandle = asynchronousInternetHandle(context->userAgent());

    if (!d->m_internetHandle)
        return false;

    DWORD flags = INTERNET_FLAG_KEEP_CONNECTION
        | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS
        | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP
        | INTERNET_FLAG_DONT_CACHE
        | INTERNET_FLAG_RELOAD;

    d->m_connectHandle = InternetConnectW(d->m_internetHandle, firstRequest().url().host().charactersWithNullTermination(), firstRequest().url().port(),
                                          0, 0, INTERNET_SERVICE_HTTP, flags, reinterpret_cast<DWORD_PTR>(this));

    if (!d->m_connectHandle)
        return false;

    String urlStr = firstRequest().url().path();
    String urlQuery = firstRequest().url().query();

    if (!urlQuery.isEmpty()) {
        urlStr.append('?');
        urlStr.append(urlQuery);
    }

    String httpMethod = firstRequest().httpMethod();
    String httpReferrer = firstRequest().httpReferrer();

    LPCWSTR httpAccept[] = { L"*/*", 0 };

    d->m_requestHandle = HttpOpenRequestW(d->m_connectHandle, httpMethod.charactersWithNullTermination(), urlStr.charactersWithNullTermination(),
                                          0, httpReferrer.charactersWithNullTermination(), httpAccept, flags, reinterpret_cast<DWORD_PTR>(this));

    if (!d->m_requestHandle) {
        InternetCloseHandle(d->m_connectHandle);
        return false;
    }

    if (firstRequest().httpBody()) {
        firstRequest().httpBody()->flatten(d->m_formData);
        d->m_bytesRemainingToWrite = d->m_formData.size();
    }

    Vector<UChar> httpHeaders;
    const HTTPHeaderMap& httpHeaderFields = firstRequest().httpHeaderFields();

    for (HTTPHeaderMap::const_iterator it = httpHeaderFields.begin(); it != httpHeaderFields.end(); ++it) {
        if (equalIgnoringCase(it->first, "Accept") || equalIgnoringCase(it->first, "Referer") || equalIgnoringCase(it->first, "User-Agent"))
            continue;

        if (!httpHeaders.isEmpty())
            httpHeaders.append('\n');

        httpHeaders.append(it->first.characters(), it->first.length());
        httpHeaders.append(':');
        httpHeaders.append(it->second.characters(), it->second.length());
    }

    INTERNET_BUFFERSW internetBuffers;
    ZeroMemory(&internetBuffers, sizeof(internetBuffers));
    internetBuffers.dwStructSize = sizeof(internetBuffers);
    internetBuffers.lpcszHeader = httpHeaders.data();
    internetBuffers.dwHeadersLength = httpHeaders.size();
    internetBuffers.dwBufferTotal = d->m_bytesRemainingToWrite;

    HttpSendRequestExW(d->m_requestHandle, &internetBuffers, 0, 0, reinterpret_cast<DWORD_PTR>(this));

    ref(); // balanced by deref in onRequestComplete

    if (d->m_loadSynchronously)
        while (onRequestComplete()) {
            // Loop until finished.
        }

    return true;
}
Example #12
0
String CIMObjectPath::toString() const
{
    String objectName;

    // Get the host:

    if (_rep->_host.size())
    {
        objectName = "//";
        objectName.append(_rep->_host);
        objectName.append("/");
    }

    // Get the namespace (if we have a host name, we must write namespace):

    if (!_rep->_nameSpace.isNull() || _rep->_host.size())
    {
        objectName.append(_rep->_nameSpace.getString ());
        objectName.append(":");
    }

    // Get the class name:

    objectName.append(getClassName().getString ());

    //
    //  ATTN-CAKG-P2-20020726:  The following condition does not correctly
    //  distinguish instanceNames from classNames in every case
    //  The instanceName of a singleton instance of a keyless class has no
    //  key bindings
    //
    if (_rep->_keyBindings.size () != 0)
    {
        objectName.append('.');

        // Append each key-value pair:

        const Array<CIMKeyBinding>& keyBindings = getKeyBindings();

        for (Uint32 i = 0, n = keyBindings.size(); i < n; i++)
        {
            objectName.append(keyBindings[i].getName().getString ());
            objectName.append('=');

            const String& value = _escapeSpecialCharacters(
                keyBindings[i].getValue());

            CIMKeyBinding::Type type = keyBindings[i].getType();

            if (type == CIMKeyBinding::STRING || type == CIMKeyBinding::REFERENCE)
                objectName.append('"');

            objectName.append(value);

            if (type == CIMKeyBinding::STRING || type == CIMKeyBinding::REFERENCE)
                objectName.append('"');

            if (i + 1 != n)
                objectName.append(',');
        }
    }

    return objectName;
}
void WebChromeClient::runOpenPanel(Frame*, PassRefPtr<FileChooser> prpFileChooser)
{
    RefPtr<FileChooser> fileChooser = prpFileChooser;

    HWND viewWindow;
    if (FAILED(m_webView->viewWindow(&viewWindow)))
        return;

    bool multiFile = fileChooser->settings().allowsMultipleFiles;
    Vector<WCHAR> fileBuf(multiFile ? maxFilePathsListSize : MAX_PATH);

    OPENFILENAME ofn;

    memset(&ofn, 0, sizeof(ofn));

    // Need to zero out the first char of fileBuf so GetOpenFileName doesn't think it's an initialization string
    fileBuf[0] = '\0';

    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = viewWindow;
    String allFiles = allFilesText();
    allFiles.append(L"\0*.*\0\0", 6);

    Vector<UChar> filterCharacters = allFiles.charactersWithNullTermination(); // Retain buffer long enough to make the GetOpenFileName call
    ofn.lpstrFilter = filterCharacters.data();

    ofn.lpstrFile = fileBuf.data();
    ofn.nMaxFile = fileBuf.size();
    String dialogTitle = uploadFileText();
    Vector<UChar> dialogTitleCharacters = dialogTitle.charactersWithNullTermination(); // Retain buffer long enough to make the GetOpenFileName call
    ofn.lpstrTitle = dialogTitleCharacters.data();
    ofn.Flags = OFN_ENABLESIZING | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_EXPLORER;
    if (multiFile)
        ofn.Flags = ofn.Flags | OFN_ALLOWMULTISELECT;

    if (GetOpenFileName(&ofn)) {
        WCHAR* files = fileBuf.data();
        Vector<String> fileList;
        String file(files);
        if (multiFile) {
            while (!file.isEmpty()) {
                // When using the OFN_EXPLORER flag, the file list is null delimited.
                // When you create a String from a ptr to this list, it will use strlen to look for the null character.
                // Then we find the next file path string by using the length of the string we just created.
                WCHAR* nextFilePtr = files + file.length() + 1;
                String nextFile(nextFilePtr);
                // If multiple files are selected, there will be a directory name first, which we don't want to add to the vector.
                // We know a single file was selected if there is only one filename in the list.  
                // In that case, we don't want to skip adding the first (and only) name.
                if (files != fileBuf.data() || nextFile.isEmpty())
                    fileList.append(file);
                files = nextFilePtr;
                file = nextFile;
            }
        } else
            fileList.append(file);
        ASSERT(fileList.size());
        fileChooser->chooseFiles(fileList);
    }
    // FIXME: Show some sort of error if too many files are selected and the buffer is too small.  For now, this will fail silently.
}
String HeapSnapshotBuilder::json(Function<bool (const HeapSnapshotNode&)> allowNodeCallback)
{
    VM& vm = m_profiler.vm();
    DeferGCForAWhile deferGC(vm.heap);

    // Build a node to identifier map of allowed nodes to use when serializing edges.
    HashMap<JSCell*, NodeIdentifier> allowedNodeIdentifiers;

    // Build a list of used class names.
    HashMap<String, unsigned> classNameIndexes;
    classNameIndexes.set("<root>"_s, 0);
    unsigned nextClassNameIndex = 1;

    // Build a list of labels (this is just a string table).
    HashMap<String, unsigned> labelIndexes;
    labelIndexes.set(emptyString(), 0);
    unsigned nextLabelIndex = 1;

    // Build a list of used edge names.
    HashMap<UniquedStringImpl*, unsigned> edgeNameIndexes;
    unsigned nextEdgeNameIndex = 0;

    StringBuilder json;

    auto appendNodeJSON = [&] (const HeapSnapshotNode& node) {
        // Let the client decide if they want to allow or disallow certain nodes.
        if (!allowNodeCallback(node))
            return;

        unsigned flags = 0;

        allowedNodeIdentifiers.set(node.cell, node.identifier);

        String className = node.cell->classInfo(vm)->className;
        if (node.cell->isObject() && className == JSObject::info()->className) {
            flags |= static_cast<unsigned>(NodeFlags::ObjectSubtype);

            // Skip calculating a class name if this object has a `constructor` own property.
            // These cases are typically F.prototype objects and we want to treat these as
            // "Object" in snapshots and not get the name of the prototype's parent.
            JSObject* object = asObject(node.cell);
            if (JSGlobalObject* globalObject = object->globalObject(vm)) {
                ExecState* exec = globalObject->globalExec();
                PropertySlot slot(object, PropertySlot::InternalMethodType::VMInquiry);
                if (!object->getOwnPropertySlot(object, exec, vm.propertyNames->constructor, slot))
                    className = JSObject::calculatedClassName(object);
            }
        }

        auto result = classNameIndexes.add(className, nextClassNameIndex);
        if (result.isNewEntry)
            nextClassNameIndex++;
        unsigned classNameIndex = result.iterator->value;

        void* wrappedAddress = 0;
        unsigned labelIndex = 0;
        if (!node.cell->isString()) {
            Structure* structure = node.cell->structure(vm);
            if (!structure || !structure->globalObject())
                flags |= static_cast<unsigned>(NodeFlags::Internal);

            if (m_snapshotType == SnapshotType::GCDebuggingSnapshot) {
                String nodeLabel;
                auto it = m_cellLabels.find(node.cell);
                if (it != m_cellLabels.end())
                    nodeLabel = it->value;

                if (nodeLabel.isEmpty()) {
                    if (auto* object = jsDynamicCast<JSObject*>(vm, node.cell)) {
                        if (auto* function = jsDynamicCast<JSFunction*>(vm, object))
                            nodeLabel = function->calculatedDisplayName(vm);
                    }
                }

                String description = descriptionForCell(node.cell);
                if (description.length()) {
                    if (nodeLabel.length())
                        nodeLabel.append(' ');
                    nodeLabel.append(description);
                }

                if (!nodeLabel.isEmpty() && m_snapshotType == SnapshotType::GCDebuggingSnapshot) {
                    auto result = labelIndexes.add(nodeLabel, nextLabelIndex);
                    if (result.isNewEntry)
                        nextLabelIndex++;
                    labelIndex = result.iterator->value;
                }

                wrappedAddress = m_wrappedObjectPointers.get(node.cell);
            }
        }

        // <nodeId>, <sizeInBytes>, <nodeClassNameIndex>, <flags>, [<labelIndex>, <cellEddress>, <wrappedAddress>]
        json.append(',');
        json.appendNumber(node.identifier);
        json.append(',');
        json.appendNumber(node.cell->estimatedSizeInBytes(vm));
        json.append(',');
        json.appendNumber(classNameIndex);
        json.append(',');
        json.appendNumber(flags);
        if (m_snapshotType == SnapshotType::GCDebuggingSnapshot) {
            json.append(',');
            json.appendNumber(labelIndex);
            json.appendLiteral(",\"0x");
            appendUnsignedAsHex(reinterpret_cast<uintptr_t>(node.cell), json, Lowercase);
            json.appendLiteral("\",\"0x");
            appendUnsignedAsHex(reinterpret_cast<uintptr_t>(wrappedAddress), json, Lowercase);
            json.append('"');
        }
    };

    bool firstEdge = true;
    auto appendEdgeJSON = [&] (const HeapSnapshotEdge& edge) {
        if (!firstEdge)
            json.append(',');
        firstEdge = false;

        // <fromNodeId>, <toNodeId>, <edgeTypeIndex>, <edgeExtraData>
        json.appendNumber(edge.from.identifier);
        json.append(',');
        json.appendNumber(edge.to.identifier);
        json.append(',');
        json.appendNumber(edgeTypeToNumber(edge.type));
        json.append(',');
        switch (edge.type) {
        case EdgeType::Property:
        case EdgeType::Variable: {
            auto result = edgeNameIndexes.add(edge.u.name, nextEdgeNameIndex);
            if (result.isNewEntry)
                nextEdgeNameIndex++;
            unsigned edgeNameIndex = result.iterator->value;
            json.appendNumber(edgeNameIndex);
            break;
        }
        case EdgeType::Index:
            json.appendNumber(edge.u.index);
            break;
        default:
            // No data for this edge type.
            json.append('0');
            break;
        }
    };

    json.append('{');

    // version
    json.appendLiteral("\"version\":2");

    // type
    json.append(',');
    json.appendLiteral("\"type\":");
    json.appendQuotedJSONString(snapshotTypeToString(m_snapshotType));

    // nodes
    json.append(',');
    json.appendLiteral("\"nodes\":");
    json.append('[');
    // <root>
    if (m_snapshotType == SnapshotType::GCDebuggingSnapshot)
        json.appendLiteral("0,0,0,0,0,\"0x0\",\"0x0\"");
    else
        json.appendLiteral("0,0,0,0");

    for (HeapSnapshot* snapshot = m_profiler.mostRecentSnapshot(); snapshot; snapshot = snapshot->previous()) {
        for (auto& node : snapshot->m_nodes)
            appendNodeJSON(node);
    }
    json.append(']');

    // node class names
    json.append(',');
    json.appendLiteral("\"nodeClassNames\":");
    json.append('[');
    Vector<String> orderedClassNames(classNameIndexes.size());
    for (auto& entry : classNameIndexes)
        orderedClassNames[entry.value] = entry.key;
    classNameIndexes.clear();
    bool firstClassName = true;
    for (auto& className : orderedClassNames) {
        if (!firstClassName)
            json.append(',');
        firstClassName = false;
        json.appendQuotedJSONString(className);
    }
    orderedClassNames.clear();
    json.append(']');

    // Process edges.
    // Replace pointers with identifiers.
    // Remove any edges that we won't need.
    m_edges.removeAllMatching([&] (HeapSnapshotEdge& edge) {
        // If the from cell is null, this means a <root> edge.
        if (!edge.from.cell)
            edge.from.identifier = 0;
        else {
            auto fromLookup = allowedNodeIdentifiers.find(edge.from.cell);
            if (fromLookup == allowedNodeIdentifiers.end()) {
                if (m_snapshotType == SnapshotType::GCDebuggingSnapshot)
                    WTFLogAlways("Failed to find node for from-edge cell %p", edge.from.cell);
                return true;
            }
            edge.from.identifier = fromLookup->value;
        }

        if (!edge.to.cell)
            edge.to.identifier = 0;
        else {
            auto toLookup = allowedNodeIdentifiers.find(edge.to.cell);
            if (toLookup == allowedNodeIdentifiers.end()) {
                if (m_snapshotType == SnapshotType::GCDebuggingSnapshot)
                    WTFLogAlways("Failed to find node for to-edge cell %p", edge.to.cell);
                return true;
            }
            edge.to.identifier = toLookup->value;
        }

        return false;
    });

    allowedNodeIdentifiers.clear();
    m_edges.shrinkToFit();

    // Sort edges based on from identifier.
    std::sort(m_edges.begin(), m_edges.end(), [&] (const HeapSnapshotEdge& a, const HeapSnapshotEdge& b) {
        return a.from.identifier < b.from.identifier;
    });

    // edges
    json.append(',');
    json.appendLiteral("\"edges\":");
    json.append('[');
    for (auto& edge : m_edges)
        appendEdgeJSON(edge);
    json.append(']');

    // edge types
    json.append(',');
    json.appendLiteral("\"edgeTypes\":");
    json.append('[');
    json.appendQuotedJSONString(edgeTypeToString(EdgeType::Internal));
    json.append(',');
    json.appendQuotedJSONString(edgeTypeToString(EdgeType::Property));
    json.append(',');
    json.appendQuotedJSONString(edgeTypeToString(EdgeType::Index));
    json.append(',');
    json.appendQuotedJSONString(edgeTypeToString(EdgeType::Variable));
    json.append(']');

    // edge names
    json.append(',');
    json.appendLiteral("\"edgeNames\":");
    json.append('[');
    Vector<UniquedStringImpl*> orderedEdgeNames(edgeNameIndexes.size());
    for (auto& entry : edgeNameIndexes)
        orderedEdgeNames[entry.value] = entry.key;
    edgeNameIndexes.clear();
    bool firstEdgeName = true;
    for (auto& edgeName : orderedEdgeNames) {
        if (!firstEdgeName)
            json.append(',');
        firstEdgeName = false;
        json.appendQuotedJSONString(edgeName);
    }
    orderedEdgeNames.clear();
    json.append(']');

    if (m_snapshotType == SnapshotType::GCDebuggingSnapshot) {
        json.append(',');
        json.appendLiteral("\"roots\":");
        json.append('[');

        HeapSnapshot* snapshot = m_profiler.mostRecentSnapshot();

        bool firstNode = true;
        for (auto it : m_rootData) {
            auto snapshotNode = snapshot->nodeForCell(it.key);
            if (!snapshotNode) {
                WTFLogAlways("Failed to find snapshot node for cell %p", it.key);
                continue;
            }

            if (!firstNode)
                json.append(',');

            firstNode = false;
            json.appendNumber(snapshotNode.value().identifier);

            // Maybe we should just always encode the root names.
            const char* rootName = rootTypeToString(it.value.markReason);
            auto result = labelIndexes.add(rootName, nextLabelIndex);
            if (result.isNewEntry)
                nextLabelIndex++;
            unsigned labelIndex = result.iterator->value;
            json.append(',');
            json.appendNumber(labelIndex);

            unsigned reachabilityReasonIndex = 0;
            if (it.value.reachabilityFromOpaqueRootReasons) {
                auto result = labelIndexes.add(it.value.reachabilityFromOpaqueRootReasons, nextLabelIndex);
                if (result.isNewEntry)
                    nextLabelIndex++;
                reachabilityReasonIndex = result.iterator->value;
            }
            json.append(',');
            json.appendNumber(reachabilityReasonIndex);
        }

        json.append(']');
    }

    if (m_snapshotType == SnapshotType::GCDebuggingSnapshot) {
        // internal node descriptions
        json.append(',');
        json.appendLiteral("\"labels\":");
        json.append('[');

        Vector<String> orderedLabels(labelIndexes.size());
        for (auto& entry : labelIndexes)
            orderedLabels[entry.value] = entry.key;
        labelIndexes.clear();
        bool firstLabel = true;
        for (auto& label : orderedLabels) {
            if (!firstLabel)
                json.append(',');

            firstLabel = false;
            json.appendQuotedJSONString(label);
        }
        orderedLabels.clear();

        json.append(']');
    }

    json.append('}');
    return json.toString();
}
PEGASUS_NAMESPACE_BEGIN

void IndicationFormatter::validateTextFormat (
    const String & textStr,
    const CIMClass & indicationClass,
    const Array<String> & textFormatParams)
{
    PEG_METHOD_ENTER (TRC_IND_FORMATTER,
	"IndicationFormatter::validateTextFormat");

    String textFormatStr = textStr;
    String textFormatSubStr;
    String exceptionStr;

    Uint32 leftBrace = textFormatStr.find("{");
    Uint32 rightBrace;

    do {
           textFormatSubStr.clear();
           if (leftBrace != PEG_NOT_FOUND)
           {
               // Do not expect a right brace before the left
               // brace. e.g An invalid text format string could be:
              // "Indication occurred at 2, datetime} with
               // identify ID {3, string}"

               textFormatSubStr = textFormatStr.subString(
                   0, leftBrace);

               Uint32 rightBrace2 = textFormatSubStr.find("}");
               if (rightBrace2 != PEG_NOT_FOUND)
               {
                   textFormatSubStr = textFormatStr.subString(
	               0, (rightBrace2 + 1));
		   MessageLoaderParms parms(
		       "IndicationFormatter.IndicationFormatter._MSG_INVALID_SYNTAX_OF_FOR_PROPERTY",
		       "Invalid syntax at $0 in property $1",
		       textFormatSubStr,
		       _PROPERTY_TEXTFORMAT.getString());

		      exceptionStr.append(
			       MessageLoader::getMessage(parms));

                     PEG_METHOD_EXIT();
		     throw PEGASUS_CIM_EXCEPTION (
		        CIM_ERR_INVALID_PARAMETER, exceptionStr);
               }

               // expect right brace
               textFormatStr = textFormatStr.subString(
			   leftBrace+1, PEG_NOT_FOUND);
               rightBrace = textFormatStr.find("}");

               // Do not expect a left brace between left and right
               // braces. e.g A text string: "Indication occurred
	      // at {2, datetime with identify ID {3, string}" is
	      // an invalid format.

             if (rightBrace != PEG_NOT_FOUND)
             {
                 textFormatSubStr.clear();
                   textFormatSubStr = textFormatStr.subString(0,
		                      rightBrace);

                 Uint32 leftBrace2 = textFormatSubStr.find("{");
                 if (leftBrace2 != PEG_NOT_FOUND)
                 {
                     textFormatSubStr = textFormatStr.subString(
		         0, (leftBrace2 + 1));
			MessageLoaderParms parms(
			"IndicationFormatter.IndicationFormatter._MSG_INVALID_SYNTAX_OF_FOR_PROPERTY",
			"Invalid syntax at $0 in property $1",
			textFormatSubStr,
			_PROPERTY_TEXTFORMAT.getString());

			exceptionStr.append(
			    MessageLoader::getMessage(parms));

                     PEG_METHOD_EXIT();
		     throw PEGASUS_CIM_EXCEPTION (
			           CIM_ERR_INVALID_PARAMETER, exceptionStr);
                }

	        String propertyParam;
	        String propertyTypeStr;
	        String propertyIndexStr;
	        char propertyIndexBuffer[32];
	        Sint32 propertyIndex;

	        Uint32 comma;
	        Uint32 leftBracket;
	        Uint32 rightBracket;
	        Boolean isArray = false;

	        comma = textFormatSubStr.find(",");

	        // A dynamic content can have format either
	       // {index} or {index[x]}
	       if (comma == PEG_NOT_FOUND)
	       {
	            propertyParam =
		        textFormatSubStr.subString(0, PEG_NOT_FOUND);
                               propertyTypeStr = String::EMPTY;

		   leftBracket = textFormatSubStr.find("[");
		           rightBracket = textFormatSubStr.find("]");

	      }
	      // A dynamic content can have format either
	     // {index, type} or {index[x], type}
	     else
	     {
	          propertyParam =
		      textFormatSubStr.subString(0, comma);
		  propertyTypeStr = textFormatSubStr.subString(
		      comma +1, PEG_NOT_FOUND);

		 leftBracket = propertyParam.find("[");
		       rightBracket = propertyParam.find("]");
             }

	    // A dynamic content has syntax either
	    // {index} or {index, type}
	    if (leftBracket == PEG_NOT_FOUND)
	    {
	        // there is no left bracket, do not expect a
	        // right bracket
	        if (rightBracket != PEG_NOT_FOUND)
	        {
	            textFormatSubStr = textFormatStr.subString(
		        0, (rightBracket + 1));
		    MessageLoaderParms parms(
		        "IndicationFormatter.IndicationFormatter._MSG_INVALID_SYNTAX_OF_FOR_PROPERTY",
		        "Invalid syntax at $0 in property $1",
		        textFormatSubStr,
		        _PROPERTY_TEXTFORMAT.getString());

		    exceptionStr.append(
		        MessageLoader::getMessage(parms));

                   PEG_METHOD_EXIT();
		   throw PEGASUS_CIM_EXCEPTION (
		       CIM_ERR_INVALID_PARAMETER, exceptionStr);
	        }

		propertyIndexStr = propertyParam;
	        isArray = false;
	    }
	   // A dynamic content has syntax either
	   // {index[]} or {index[], type}
	   else
           {
	       // there is a left bracket, expect a right bracket
	       if (rightBracket == PEG_NOT_FOUND)
	       {
	           MessageLoaderParms parms(
		       "IndicationFormatter.IndicationFormatter._MSG_INVALID_SYNTAX_OF_FOR_PROPERTY",
		       "Invalid syntax at $0 in property $1",
		       textFormatSubStr,
		       _PROPERTY_TEXTFORMAT.getString());

		   exceptionStr.append(
		       MessageLoader::getMessage(parms));

                   PEG_METHOD_EXIT();
		   throw PEGASUS_CIM_EXCEPTION (
		       CIM_ERR_INVALID_PARAMETER, exceptionStr);
	       }

	           propertyIndexStr =
		       propertyParam.subString(0, leftBracket);

		   isArray = true;
           }

           sprintf(propertyIndexBuffer, "%s",
	       (const char *)propertyIndexStr.getCString());

           // skip white space
           char * indexStr = propertyIndexBuffer;
           while (*indexStr && isspace(*indexStr))
           {
               *indexStr++;
           }

           _isValidIndex(indexStr);

	   propertyIndex = atoi(indexStr);

           // check the property index
           if ((propertyIndex < 0) ||
	       ((Uint32)propertyIndex >= textFormatParams.size()))
           {
	       // property index is out of bounds
	       MessageLoaderParms parms(
	       "IndicationFormatter.IndicationFormatter._MSG_INDEX_IS_OUT_OF_BOUNDS",
	       "The value of index $0 in property $1 is out of bounds",
	       propertyIndex,
	       _PROPERTY_TEXTFORMATPARAMETERS.getString());

	       exceptionStr.append(MessageLoader::getMessage(parms));

	       PEG_METHOD_EXIT();
	       throw PEGASUS_CIM_EXCEPTION (CIM_ERR_INVALID_PARAMETER, exceptionStr);
           }

	   if (propertyTypeStr != String::EMPTY)
	   {
	       _validatePropertyType(indicationClass,
	           textFormatParams[propertyIndex],
		   propertyTypeStr, isArray);
           }

           textFormatStr = textFormatStr.subString(
	       rightBrace+1, PEG_NOT_FOUND);
          }
         else // no right brace
         {
             MessageLoaderParms parms(
	        "IndicationFormatter.IndicationFormatter._MSG_INVALID_SYNTAX_OF_FOR_PROPERTY",
	        "Invalid syntax at $0 in property $1",
	        textFormatSubStr,
	        _PROPERTY_TEXTFORMAT.getString());

	    exceptionStr.append(
	        MessageLoader::getMessage(parms));

           PEG_METHOD_EXIT();
	   throw PEGASUS_CIM_EXCEPTION (
	       CIM_ERR_INVALID_PARAMETER, exceptionStr);
         }
        }
        else // no left brace
        {
            // does not expect right brace
           rightBrace = textFormatStr.find("}");

           if (rightBrace != PEG_NOT_FOUND)
           {
	       textFormatSubStr = textFormatStr.subString(
	           0, (rightBrace + 1));
	       MessageLoaderParms parms(
	           "IndicationFormatter.IndicationFormatter._MSG_INVALID_SYNTAX_OF_FOR_PROPERTY",
	           "Invalid syntax at $0 in property $1",
		   textFormatSubStr,
		   _PROPERTY_TEXTFORMAT.getString());

		   exceptionStr.append(
		   MessageLoader::getMessage(parms));

                  PEG_METHOD_EXIT();
		  throw PEGASUS_CIM_EXCEPTION (
		    CIM_ERR_INVALID_PARAMETER, exceptionStr);
            }

           break;
       }

         leftBrace = textFormatStr.find("{");
     } while (textFormatStr.size() > 0);

    PEG_METHOD_EXIT();
}
Example #16
0
/**

    Parses the command line, validates the options, and sets instance
    variables based on the option arguments.

    @param   argc  the number of command line arguments
    @param   argv  the string vector of command line arguments

    @exception  CommandFormatException  if an error is encountered in parsing
                                        the command line

 */
void OSInfoCommand::setCommand (Uint32 argc, char* argv [])
{
    Uint32         i              = 0;
    Uint32         c              = 0;
    String         httpVersion    = String ();
    String         httpMethod     = String ();
    String         timeoutStr     = String ();
    String         GetOptString   = String ();
    getoopt        getOpts;

    _operationType = OPERATION_TYPE_UNINITIALIZED;
    //
    //  Construct GetOptString
    //
#ifndef DISABLE_SUPPORT_FOR_REMOTE_CONNECTIONS
    GetOptString.append (_OPTION_HOSTNAME);
    GetOptString.append (getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    GetOptString.append (_OPTION_PORTNUMBER);
    GetOptString.append (getoopt::GETOPT_ARGUMENT_DESIGNATOR);
#ifdef PEGASUS_HAS_SSL
    GetOptString.append (_OPTION_SSL);
#endif
    GetOptString.append (_OPTION_TIMEOUT);
    GetOptString.append (getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    GetOptString.append (_OPTION_USERNAME);
    GetOptString.append (getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    GetOptString.append (_OPTION_PASSWORD);
    GetOptString.append (getoopt::GETOPT_ARGUMENT_DESIGNATOR);
#endif
    GetOptString.append (_OPTION_RAW_DATETIME_FORMAT);

    //
    //  Initialize and parse getOpts
    //
    getOpts = getoopt ();
    getOpts.addFlagspec (GetOptString);

    //PEP#167 - adding long flag for options : 'help' and 'version'
    getOpts.addLongFlagspec(LONG_HELP,getoopt::NOARG);
    getOpts.addLongFlagspec(LONG_VERSION,getoopt::NOARG);

    getOpts.parse (argc, argv);

    if (getOpts.hasErrors ())
    {
        throw CommandFormatException(getOpts.getErrorStrings()[0]);
    }

    //
    //  Get options and arguments from the command line
    //
    for (i =  getOpts.first (); i <  getOpts.last (); i++)
    {
        if (getOpts[i].getType () == Optarg::LONGFLAG)
        {
            if (getOpts[i].getopt () == LONG_HELP)
            {
                if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                {
                    String param = String (LONG_HELP);
                    //
                    // More than one operation option was found
                    //
                    throw UnexpectedOptionException(param);
                }

               _operationType = OPERATION_TYPE_HELP;
            }
            else if (getOpts[i].getopt () == LONG_VERSION)
            {
                if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                {
                    //
                    // More than one operation option was found
                    //
                    throw UnexpectedOptionException(String(LONG_VERSION));
                }

               _operationType = OPERATION_TYPE_VERSION;
            }
        }
        else if (getOpts [i].getType () == Optarg::REGULAR)
        {
            throw UnexpectedArgumentException(getOpts[i].Value());
        }
        else /* getOpts [i].getType () == FLAG */
        {
            c = getOpts [i].getopt () [0];
            switch (c)
            {
                case _OPTION_HOSTNAME:
                {
                    if (getOpts.isSet (_OPTION_HOSTNAME) > 1)
                    {
                        //
                        // More than one hostname option was found
                        //
                        throw DuplicateOptionException(_OPTION_HOSTNAME);
                    }
                    _hostName = getOpts [i].Value ();
                    HostAddress addr(_hostName);
                    if (!addr.isValid())
                    {
                        throw InvalidLocatorException (_hostName);
                    }
                    _hostNameSet = true;
                    break;
                }

                case _OPTION_PORTNUMBER:
                {
                    if (getOpts.isSet (_OPTION_PORTNUMBER) > 1)
                    {
                        //
                        // More than one portNumber option was found
                        //
                        throw DuplicateOptionException(_OPTION_PORTNUMBER);
                    }

                    _portNumberStr = getOpts [i].Value ();

                    try
                    {
                        getOpts [i].Value (_portNumber);
                    }
                    catch (const TypeMismatchException&)
                    {
                        throw InvalidOptionArgumentException(
                            _portNumberStr,
                            _OPTION_PORTNUMBER);
                    }
                    _portNumberSet = true;
                    break;
                }

                case _OPTION_SSL:
                {
                    //
                    // Use port 5989 as the default port for SSL
                    //
                    _useSSL = true;
                    if (!_portNumberSet)
                       _portNumber = 5989;
                    break;
                }

                case _OPTION_RAW_DATETIME_FORMAT:
                {
                    //
                    // Display "raw" CIM_DateTime format.
                    //
                    _useRawDateTimeFormat = true;
                    break;
                }

                case _OPTION_TIMEOUT:
                {
                    if (getOpts.isSet (_OPTION_TIMEOUT) > 1)
                    {
                        //
                        // More than one timeout option was found
                        //
                        throw DuplicateOptionException(_OPTION_TIMEOUT);
                    }

                    timeoutStr = getOpts [i].Value ();

                    try
                    {
                        getOpts [i].Value (_timeout);
                    }
                    catch (const TypeMismatchException&)
                    {
                        throw InvalidOptionArgumentException(
                            timeoutStr,
                            _OPTION_TIMEOUT);
                    }
                    break;
                }

                case _OPTION_USERNAME:
                {
                    if (getOpts.isSet (_OPTION_USERNAME) > 1)
                    {
                        //
                        // More than one username option was found
                        //
                        throw DuplicateOptionException(_OPTION_USERNAME);
                    }
                    _userName = getOpts [i].Value ();
                    _userNameSet = true;
                    break;
                }

                case _OPTION_PASSWORD:
                {
                    if (getOpts.isSet (_OPTION_PASSWORD) > 1)
                    {
                        //
                        // More than one password option was found
                        //
                        throw DuplicateOptionException(_OPTION_PASSWORD);
                    }
                    _password = getOpts [i].Value ();
                    _passwordSet = true;
                    break;
                }

                default:
                    //
                    //  This path should not be hit
                    //  PEP#167 unless an empty '-' is specified
                    //_operationType = OPERATION_TYPE_UNINITIALIZED;
                    break;
            }
        }
    }

    //
    // Some more validations
    //
    /*if ( _operationType == OPERATION_TYPE_UNINITIALIZED )
    {
        //
        // No operation type was specified
        // Show the usage
        //
        throw CommandFormatException(localizeMessage(
            MSG_PATH,
            REQUIRED_ARGS_MISSING_KEY,
            REQUIRED_ARGS_MISSING));
    }*/
    if (getOpts.isSet (_OPTION_PORTNUMBER) < 1)
    {
        //
        //  No portNumber specified
        //  Default to WBEM_DEFAULT_PORT
        //  Already done in constructor
        //
    }
    else
    {
        if (_portNumber > _MAX_PORTNUMBER)
        {
            //
            //  Portnumber out of valid range
            //
            throw InvalidOptionArgumentException(
                _portNumberStr,
                _OPTION_PORTNUMBER);
        }
    }

    if (getOpts.isSet (_OPTION_TIMEOUT) < 1)
    {
        //
        //  No timeout specified
        //  Default to DEFAULT_TIMEOUT_MILLISECONDS
        //  Already done in constructor
        //
    }
    else
    {
        if (_timeout == 0)
        {
            //
            //  Timeout out of valid range
            //
            throw InvalidOptionArgumentException(timeoutStr, _OPTION_TIMEOUT);
        }
    }
}
void IndicationFormatter::_isValidIndex (
    const char * indexStr)
{

    PEG_METHOD_ENTER (TRC_IND_FORMATTER,
	"IndicationFormatter::_isValidIndex");

    String exceptionStr;

    String indexSubStr = indexStr;
    Uint32 space = indexSubStr.find(" ");
    if (space != PEG_NOT_FOUND)
    {
        String restIndexSubStr = indexSubStr.subString(space, PEG_NOT_FOUND);

        // skip the appended space from the indexSubStr
        Uint32 k=0;
        while (restIndexSubStr[k] == ' ') 
        {
            k++;
        }

        restIndexSubStr = restIndexSubStr.subString(k, PEG_NOT_FOUND);

        if (restIndexSubStr.size() == 0)
        {
            indexSubStr = indexSubStr.subString(0, space);
        }
        // invalid index string [12 xxx]
        else
        {
            // invalid index string
            MessageLoaderParms parms(
                "IndicationFormatter.IndicationFormatter._MSG_INVALID_INDEX",
                "Invalid index string $0",
                indexStr);

            exceptionStr.append(MessageLoader::getMessage(parms));

            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION (
                CIM_ERR_INVALID_PARAMETER, exceptionStr);

        }
    }

    Uint32 i=0;
    while ((indexSubStr[i] >= '0') && (indexSubStr[i] <= '9'))
    {
        i++;
    }

    // invalid index string [12xxx}
    if (i != indexSubStr.size() )
    {
        // invalid index string
        MessageLoaderParms parms(
            "IndicationFormatter.IndicationFormatter._MSG_INVALID_INDEX",
            "Invalid index string $0",
            indexStr);
        exceptionStr.append(MessageLoader::getMessage(parms));

        PEG_METHOD_EXIT();
        throw PEGASUS_CIM_EXCEPTION (
            CIM_ERR_INVALID_PARAMETER, exceptionStr);
    }

    PEG_METHOD_EXIT();
}
Example #18
0
int
FileChunk::assemble(synergy::IStream* stream, String& dataReceived, size_t& expectedSize)
{
	// parse
	UInt8 mark = 0;
	String content;
	static size_t receivedDataSize;
	static double elapsedTime;
	static Stopwatch stopwatch;

	if (!ProtocolUtil::readf(stream, kMsgDFileTransfer + 4, &mark, &content)) {
		return kError;
	}

	switch (mark) {
	case kDataStart:
		dataReceived.clear();
		expectedSize = synergy::string::stringToSizeType(content);
		receivedDataSize = 0;
		elapsedTime = 0;
		stopwatch.reset();

		if (CLOG->getFilter() >= kDEBUG2) {
			LOG((CLOG_DEBUG2 "recv file data from client: file size=%s", content.c_str()));
			stopwatch.start();
		}
		return kStart;

	case kDataChunk:
		dataReceived.append(content);
		if (CLOG->getFilter() >= kDEBUG2) {
				LOG((CLOG_DEBUG2 "recv file data from client: chunck size=%i", content.size()));
				double interval = stopwatch.getTime();
				receivedDataSize += content.size();
				LOG((CLOG_DEBUG2 "recv file data from client: interval=%f s", interval));
				if (interval >= kIntervalThreshold) {
					double averageSpeed = receivedDataSize / interval / 1000;
					LOG((CLOG_DEBUG2 "recv file data from client: average speed=%f kb/s", averageSpeed));

					receivedDataSize = 0;
					elapsedTime += interval;
					stopwatch.reset();
				}
			}
		return kNotFinish;

	case kDataEnd:
		if (expectedSize != dataReceived.size()) {
			LOG((CLOG_ERR "corrupted clipboard data, expected size=%d actual size=%d", expectedSize, dataReceived.size()));
			LOG((CLOG_NOTIFY "File Transmission Failed: Corrupted file data."));
			return kError;
		}

		if (CLOG->getFilter() >= kDEBUG2) {
			LOG((CLOG_DEBUG2 "file data transfer finished"));
			elapsedTime += stopwatch.getTime();
			double averageSpeed = expectedSize / elapsedTime / 1000;
			LOG((CLOG_DEBUG2 "file data transfer finished: total time consumed=%f s", elapsedTime));
			LOG((CLOG_DEBUG2 "file data transfer finished: total data received=%i kb", expectedSize / 1000));
			LOG((CLOG_DEBUG2 "file data transfer finished: total average speed=%f kb/s", averageSpeed));
		}
		return kFinish;
	}

	return kError;
}
String IndicationFormatter::_formatIndicationText(
    const String & textFormat,
    const Array<String>& textFormatParams,
    const CIMInstance & indication,
    const ContentLanguages & contentLangs)
{
    PEG_METHOD_ENTER (TRC_IND_FORMATTER,
        "IndicationFormatter::_formatIndicationText");

    String indicationText;
    String textStr;
    String indicationFormat = textFormat;
    String propertyValue;
    String propertyParam;

    String propertyIndexStr;
    char propertyIndexBuffer[16];
    Sint32 propertyIndex;

    Uint32 leftBrace = textFormat.find("{");
    Uint32 rightBrace;
    Uint32 comma;
    Uint32 leftBracket;
    Uint32 rightBracket;

    String arrayIndexStr;

    indicationText.clear();

    // Parsing the specified indication text format.
    // As an example, a format string for a UPS AlertIndication
    // could be defined as follows: A {4, string} UPS Alert was
    // detected on the device {6[1]}.
    while (leftBrace != PEG_NOT_FOUND)
    {
	textStr.clear();
	propertyParam.clear();
	propertyIndexStr.clear();
	arrayIndexStr.clear();

        // there is a left brace
        textStr = indicationFormat.subString(0, leftBrace);

        indicationText.append(textStr);

        indicationFormat = indicationFormat.subString(leftBrace+1,
                                                      PEG_NOT_FOUND);
        rightBrace = indicationFormat.find("}");

        // expecting a right brace
        if (rightBrace != PEG_NOT_FOUND)
        {
            // gets property index which is inside braces.
            // The supported formats are: {index} or {index, type}
	    // or {index[x]} or {index[x], type}
            propertyParam = indicationFormat.subString(0,
                                                       rightBrace);
            comma = propertyParam.find(",");

	    // A dynamic content has syntax {index, type} or {index[x], type}
            if (comma != PEG_NOT_FOUND)
            {
		propertyParam = propertyParam.subString(0, comma);
            }

	    leftBracket = propertyParam.find("[");

	    // A dynamic content has syntax {index} or {index, type}
	    if (leftBracket == PEG_NOT_FOUND)
	    {
                propertyIndexStr = propertyParam;
	    }
	    // A dynamic content has syntax {index[x]} or {index[x], type}
	    else
	    {
	        propertyIndexStr = propertyParam.subString(0,leftBracket);

		propertyParam = propertyParam.subString(
		    leftBracket, PEG_NOT_FOUND);

	        rightBracket = propertyParam.find("]");

		arrayIndexStr = propertyParam.subString(1, rightBracket-1);
	    }

            sprintf(propertyIndexBuffer, "%s", (const char *)
	        propertyIndexStr.getCString());
	    try
	    {
		_isValidIndex(propertyIndexBuffer);
                propertyIndex = atoi(propertyIndexBuffer);
	    }
	    catch (CIMException & c)
	    {
		propertyIndex = -1;

		PEG_TRACE_STRING(TRC_IND_FORMATTER, Tracer::LEVEL4, c.getMessage());
	    }


            // property index is out of range
            if ((propertyIndex < 0) ||
                ((Uint32)propertyIndex >= textFormatParams.size()))
            {
		propertyValue = "UNKNOWN";
            }
            else
	    {

                // get indication property value
                propertyValue = _getIndPropertyValue(
                    textFormatParams[propertyIndex],
		    arrayIndexStr,
                    indication,
		    contentLangs);
            }

            indicationText.append(propertyValue);
        }

        indicationFormat = indicationFormat.subString(rightBrace+1,
                                                      PEG_NOT_FOUND);

        leftBrace = indicationFormat.find("{");

    }

    indicationText.append(indicationFormat);

    PEG_METHOD_EXIT();

    return (indicationText);
}
    //-----------------------------------------------------------------------
    void FileSystemArchive::findFiles(const String& pattern, bool recursive, 
        bool dirs, StringVector* simpleList, FileInfoList* detailList)
    {
        long lHandle, res;
        struct _finddata_t tagData;

        // pattern can contain a directory name, separate it from mask
        size_t pos1 = pattern.rfind ('/');
        size_t pos2 = pattern.rfind ('\\');
        if (pos1 == pattern.npos || ((pos2 != pattern.npos) && (pos1 < pos2)))
            pos1 = pos2;
        String directory;
        if (pos1 != pattern.npos)
            directory = pattern.substr (0, pos1 + 1);

        String full_pattern = concatenate_path(mName, pattern);

        lHandle = _findfirst(full_pattern.c_str(), &tagData);
        res = 0;
        while (lHandle != -1 && res != -1)
        {
            if ((dirs == ((tagData.attrib & _A_SUBDIR) != 0)) &&
				( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
                (!dirs || !is_reserved_dir (tagData.name)))
            {
                if (simpleList)
                {
                    simpleList->push_back(directory + tagData.name);
                }
                else if (detailList)
                {
                    FileInfo fi;
                    fi.archive = this;
                    fi.filename = directory + tagData.name;
                    fi.basename = tagData.name;
                    fi.path = directory;
                    fi.compressedSize = tagData.size;
                    fi.uncompressedSize = tagData.size;
                    detailList->push_back(fi);
                }
            }
            res = _findnext( lHandle, &tagData );
        }
        // Close if we found any files
        if(lHandle != -1)
            _findclose(lHandle);

        // Now find directories
        if (recursive)
        {
            String base_dir = mName;
            if (!directory.empty ())
            {
                base_dir = concatenate_path(mName, directory);
                // Remove the last '/'
                base_dir.erase (base_dir.length () - 1);
            }
            base_dir.append ("/*");

            // Remove directory name from pattern
            String mask ("/");
            if (pos1 != pattern.npos)
                mask.append (pattern.substr (pos1 + 1));
            else
                mask.append (pattern);

            lHandle = _findfirst(base_dir.c_str (), &tagData);
            res = 0;
            while (lHandle != -1 && res != -1)
            {
                if ((tagData.attrib & _A_SUBDIR) &&
					( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
                    !is_reserved_dir (tagData.name))
                {
                    // recurse
                    base_dir = directory;
                    base_dir.append (tagData.name).append (mask);
                    findFiles(base_dir, recursive, dirs, simpleList, detailList);
                }
                res = _findnext( lHandle, &tagData );
            }
            // Close if we found any files
            if(lHandle != -1)
                _findclose(lHandle);
        }
    }
Example #21
0
bool
TestConnect::PerformTest(ConnectionSecurity connection_security, const String  &localAddressStr, const String &server, int port, String &result)
{
    std::shared_ptr<IOService> io_service_wrapper = Application::Instance()->GetIOService();

    IPAddress localAddress;
    if (!localAddressStr.IsEmpty())
    {
        if (!localAddress.TryParse(localAddressStr, false))
        {
            result.append(Formatter::Format("ERROR: Unable to parse address {0}.\r\n", localAddressStr));
            return false;
        }
        else
            result.append(Formatter::Format("Local address is {0}.\r\n", localAddress.ToString()));
    }

    result.append(Formatter::Format("Trying to connect to host {0}...\r\n", server));


    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service_wrapper->GetIOService());
    tcp::resolver::query query(AnsiString(server), AnsiString(StringParser::IntToString(port)), tcp::resolver::query::numeric_service);
    boost::system::error_code errorResolve = boost::asio::error::host_not_found;
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query, errorResolve);
    tcp::resolver::iterator end;

    if (errorResolve || endpoint_iterator == end)
    {
        // Host was not found.
        String formattedString;
        formattedString.Format(_T("ERROR: The host name %s could not be resolved.\r\n"), server.c_str());

        result.append(formattedString);
        return false;
    }

    String last_error_message;

    // Try each endpoint until we successfully establish a connection.
    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && endpoint_iterator != end)
    {
        boost::asio::ip::address adr = (*endpoint_iterator).endpoint().address();

        String ipAddressString = adr.to_string();
        String formattedString;
        formattedString.Format(_T("Trying to connect to TCP/IP address %s on port %d.\r\n"), ipAddressString.c_str(), port);
        result.append(formattedString);


        std::shared_ptr<Event> disconnectEvent = std::shared_ptr<Event>(new Event());

        std::shared_ptr<TestConnectionResult> connection_result = std::make_shared<TestConnectionResult>();

        std::shared_ptr<TestConnection> connection = std::make_shared<TestConnection>(connection_security, io_service_wrapper->GetIOService(), io_service_wrapper->GetClientContext(), disconnectEvent, server, connection_result);
        if (connection->Connect(ipAddressString, port, localAddress))
        {
            connection.reset();

            disconnectEvent->Wait();

            if (connection_result->GetConnectedSuccesfully())
            {
                result.append(_T("Connected successfully.\r\n"));

                if (connection_security == CSSSL)
                {
                    if (connection_result->GetHandshakeCompletedSuccesfully())
                    {
                        result.append(_T("SSL/TLS handshake completed successfully.\r\n"));
                        return true;
                    }
                    else
                    {
                        result.append(_T("ERROR: Handshake failed.\r\n"));
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                result.append(Formatter::Format("ERROR: It was not possible to connect. Error: {0}.\r\n", connection_result->GetErrorMessage()));
            }
        }

        endpoint_iterator++;
    }

    // We were unable to connect.
    result.append(_T("ERROR: Failed to connect to all servers.\r\n"));
    return false;
}
String CookieManager::generateHtmlFragmentForCookies()
{
    CookieLog("CookieManager - generateHtmlFragmentForCookies\n");

    Vector<ParsedCookie*> cookieCandidates;
    for (HashMap<String, CookieMap*>::iterator it = m_managerMap.begin(); it != m_managerMap.end(); ++it)
        it->value->getAllChildCookies(&cookieCandidates);

    String result;
    ParsedCookie* cookie = 0;
    result.append(String("<table style=\"word-wrap:break-word\" cellSpacing=\"0\" cellPadding=\"0\" border=\"1\"><tr><th>Domain</th><th>Path</th><th>Protocol</th><th>Name</th><th>Value</th><th>Secure</th><th>HttpOnly</th><th>Session</th></tr>"));
    for (size_t i = 0; i < cookieCandidates.size(); ++i) {
        cookie = cookieCandidates[i];
        result.append(String("<tr><td align=\"center\">"));
        result.append(cookie->domain());
        result.append(String("<td align=\"center\">"));
        result.append(cookie->path());
        result.append(String("<td align=\"center\">"));
        result.append(cookie->protocol());
        result.append(String("<td align=\"center\">"));
        result.append(cookie->name());
        result.append(String("<td align=\"center\" style= \"word-break:break-all\">"));
        result.append(cookie->value());
        result.append(String("<td align=\"center\">"));
        result.append(String(cookie->isSecure() ? "Yes" : "No"));
        result.append(String("<td align=\"center\">"));
        result.append(String(cookie->isHttpOnly() ? "Yes" : "No"));
        result.append(String("<td align=\"center\">"));
        result.append(String(cookie->isSession() ? "Yes" : "No"));
        result.append(String("</td></tr>"));
    }
    result.append(String("</table>"));
    return result;
}
bool FTPDirectoryTokenizer::write(const SegmentedString& s, bool appendData)
{    
    // Make sure we have the table element to append to by loading the template set in the pref, or
    // creating a very basic document with the appropriate table
    if (!m_tableElement) {
        if (!loadDocumentTemplate())
            createBasicDocument();
        ASSERT(m_tableElement);
    }
        
    bool foundNewLine = false;
    
    m_dest = m_buffer;
    SegmentedString str = s;
    while (!str.isEmpty()) {
        UChar c = *str;
        
        if (c == '\r') {
            *m_dest++ = '\n';
            foundNewLine = true;
            // possibly skip an LF in the case of an CRLF sequence
            m_skipLF = true;
        } else if (c == '\n') {
            if (!m_skipLF)
                *m_dest++ = c;
            else
                m_skipLF = false;
        } else {
            *m_dest++ = c;
            m_skipLF = false;
        }
        
        str.advance();
        
        // Maybe enlarge the buffer
        checkBuffer();
    }
    
    if (!foundNewLine) {
        m_dest = m_buffer;
        return false;
    }

    UChar* start = m_buffer;
    UChar* cursor = start;
    
    while (cursor < m_dest) {
        if (*cursor == '\n') {
            m_carryOver.append(String(start, cursor - start));
            LOG(FTP, "%s", m_carryOver.ascii().data());
            parseAndAppendOneLine(m_carryOver);
            m_carryOver = String();

            start = ++cursor;
        } else 
            cursor++;
    }
    
    // Copy the partial line we have left to the carryover buffer
    if (cursor - start > 1)
        m_carryOver.append(String(start, cursor - start - 1));
    
    return false;
}
Example #24
0
String Symbol::toString(Flags<ToStringFlag> cursorInfoFlags,
                        Flags<Location::ToStringFlag> locationToStringFlags,
                        const std::shared_ptr<Project> &project) const
{
    auto properties = [this]()
    {
        List<String> ret;
        if (isDefinition())
            ret << "Definition";
        if (isContainer())
            ret << "Container";
        if ((flags & PureVirtualMethod) == PureVirtualMethod) {
            ret << "Pure Virtual";
        } else if (flags & VirtualMethod) {
            ret << "Virtual";
        }

        if (flags & ConstMethod) {
            ret << "Const";
        } else if (flags & StaticMethod) {
            ret << "Static";
        }

        if (flags & Variadic)
            ret << "Variadic";
        if (flags & Auto)
            ret << "Auto";
        if (flags & AutoRef)
            ret << "AutoRef";

        if (flags & MacroExpansion)
            ret << "MacroExpansion";
        if (flags & TemplateSpecialization)
            ret << "TemplateSpecialization";

        if (ret.isEmpty())
            return String();
        String joined = String::join(ret, ' ');
        joined += '\n';
        return joined;
    };

    List<String> bases;
    if (project) {
        extern String findSymbolNameByUsr(const std::shared_ptr<Project> &, const String &, const Location &location);
        for (const auto &base : baseClasses) {
            const String symbolName = findSymbolNameByUsr(project, base, location);
            if (!symbolName.isEmpty()) {
                bases << symbolName;
            }
        }
    } else {
        bases = baseClasses;
    }

    auto printTypeName = [this]() {
        String str;
        if (!typeName.isEmpty()) {
            str = typeName;
        } else if (type != CXType_Invalid) {
            str = RTags::eatString(clang_getTypeKindSpelling(type));
        } else {
            return String();
        }
        return String::format<128>("Type: %s\n", str.constData());
    };

    String ret = String::format<1024>("SymbolName: %s\n"
                                      "Kind: %s\n"
                                      "%s" // type
                                      "SymbolLength: %u\n"
                                      "%s" // range
                                      "%s" // enumValue
                                      "%s" // linkage
                                      "%s" // properties
                                      "%s" // usr
                                      "%s" // sizeof
                                      "%s" // fieldoffset
                                      "%s" // baseclasses
                                      "%s" // briefComment
                                      "%s", // xmlComment
                                      symbolName.constData(),
                                      kindSpelling().constData(),
                                      printTypeName().constData(),
                                      symbolLength,
                                      startLine != -1 ? String::format<32>("Range: %d:%d-%d:%d\n", startLine, startColumn, endLine, endColumn).constData() : "",
#if CINDEX_VERSION_MINOR > 1
                                      kind == CXCursor_EnumConstantDecl ? String::format<32>("Enum Value: %lld\n", enumValue).constData() :
#endif
                                      "",
                                      linkageSpelling(linkage),
                                      properties().constData(),
                                      usr.isEmpty() ? "" : String::format<64>("Usr: %s\n", usr.constData()).constData(),
                                      size > 0 ? String::format<16>("sizeof: %d\n", size).constData() : "",
                                      fieldOffset >= 0 ? String::format<32>("field offset (bits/bytes): %d/%d\n", fieldOffset, fieldOffset / 8).constData() : "",
                                      alignment >= 0 ? String::format<32>("alignment (bytes): %d\n", alignment).constData() : "",
                                      bases.isEmpty() ? "" : String::format<64>("BaseClasses: %s\n", String::join(bases, ", ").constData()).constData(),
                                      briefComment.isEmpty() ? "" : String::format<1024>("Brief comment: %s\n", briefComment.constData()).constData(),
                                      xmlComment.isEmpty() ? "" : String::format<16384>("Xml comment: %s\n", xmlComment.constData()).constData());
    if (!(cursorInfoFlags & IgnoreTargets) && project) {
        extern Set<Symbol> findTargets(const std::shared_ptr<Project> &, const Symbol &);
        auto targets = findTargets(project, *this);
        if (targets.size()) {
            ret.append("Targets:\n");
            auto best = RTags::bestTarget(targets);
            ret.append(String::format<128>("    %s\n", best.location.toString(locationToStringFlags).constData()));

            for (const auto &tit : targets) {
                if (tit.location != best.location)
                    ret.append(String::format<128>("    %s\n", tit.location.toString(locationToStringFlags).constData()));
            }
        }
    }

    if (!(cursorInfoFlags & IgnoreReferences) && project && !isReference()) {
        extern Set<Symbol> findCallers(const std::shared_ptr<Project> &, const Symbol &);
        auto references = findCallers(project, *this);
        if (references.size()) {
            ret.append("References:\n");
            for (const auto &r : references) {
                ret.append(String::format<128>("    %s\n", r.location.toString(locationToStringFlags).constData()));
            }
        }
    }

    return ret;
}
Example #25
0
void Test01(Uint32 mode)
{
    String repositoryRoot;
    const char* tmpDir = getenv ("PEGASUS_TMP");
    if (tmpDir == NULL)
    {
        repositoryRoot = ".";
    }
    else
    {
        repositoryRoot = tmpDir;
    }

    repositoryRoot.append("/repository");

    FileSystem::removeDirectoryHier(repositoryRoot);

    CIMRepository r (repositoryRoot, mode);

    // Create a namespace:

    const CIMNamespaceName NAMESPACE = CIMNamespaceName ("zzz");
    r.createNameSpace(NAMESPACE);

    // Create a qualifier (and read it back):

    CIMQualifierDecl q1(CIMName ("abstract"), false, CIMScope::CLASS);
    r.setQualifier(NAMESPACE, q1);

    CIMConstQualifierDecl q2 = r.getQualifier(NAMESPACE, CIMName ("abstract"));
    PEGASUS_TEST_ASSERT(q1.identical(q2));

    // Create two simple classes:

    CIMClass class1(CIMName ("Class1"));
    class1.addQualifier(
        CIMQualifier(CIMName ("abstract"), true, CIMFlavor::DEFAULTS));
    CIMClass class2(CIMName ("Class2"), CIMName ("Class1"));

    r.createClass(NAMESPACE, class1);
    r.createClass(NAMESPACE, class2);

    // Enumerate the class names:
    Array<CIMName> classNames =
        r.enumerateClassNames(NAMESPACE, CIMName(), true);

    BubbleSort(classNames);

    PEGASUS_TEST_ASSERT(classNames.size() == 2);
    PEGASUS_TEST_ASSERT(classNames[0] == "Class1");
    PEGASUS_TEST_ASSERT(classNames[1] == "Class2");

    // Get the classes and determine if they are identical with input

    CIMClass c1 = r.getClass(NAMESPACE, CIMName ("Class1"), true, true, false);
    CIMClass c2 = r.getClass(NAMESPACE, CIMName ("Class2"), true, true, false);

    PEGASUS_TEST_ASSERT(c1.identical(class1));
    PEGASUS_TEST_ASSERT(c1.identical(class1));

    Array<CIMClass> classes =
        r.enumerateClasses(NAMESPACE, CIMName (), true, true, true);

    // Attempt to delete Class1. It should fail since the class has
    // children.

    try
    {
        r.deleteClass(NAMESPACE, CIMName ("Class1"));
    }
    catch (CIMException& e)
    {
        PEGASUS_TEST_ASSERT(e.getCode() == CIM_ERR_CLASS_HAS_CHILDREN);
    }

    // Delete all classes created here:

    r.deleteClass(NAMESPACE, CIMName ("Class2"));
    r.deleteClass(NAMESPACE, CIMName ("Class1"));

    // Be sure the classes are really gone:

    try
    {
        CIMClass c1 = r.getClass(
            NAMESPACE, CIMName ("Class1"), true, true, true);
        PEGASUS_TEST_ASSERT(false);
    }
    catch (CIMException& e)
    {
        PEGASUS_TEST_ASSERT(e.getCode() == CIM_ERR_NOT_FOUND);
    }

    try
    {
        CIMClass c2 = r.getClass(
            NAMESPACE, CIMName ("Class2"), true, true, true);
        PEGASUS_TEST_ASSERT(false);
    }
    catch (CIMException& e)
    {
        PEGASUS_TEST_ASSERT(e.getCode() == CIM_ERR_NOT_FOUND);
    }

    FileSystem::removeDirectoryHier(repositoryRoot);
}
String IndicationFormatter::_getArrayValues(
    const CIMValue & propertyValue,
    const String & arrayIndexStr,
    const ContentLanguages & contentLangs)
{
    PEG_METHOD_ENTER (TRC_IND_FORMATTER,
	"IndicationFormatter::_getArrayValues");

    CIMType type = propertyValue.getType();
    String arrayValues;
    char propertyValueBuffer[2048];
    Uint32 arraySize = propertyValue.getArraySize();

    char arrayIndexBuffer[16];
    Sint32 arrayIndex = 0;
    Uint32 sizeOfArrayIndexStr = arrayIndexStr.size();

    // there is an index value enclosed in brackets (e.g. [2])
    if (sizeOfArrayIndexStr != 0)
    {
        sprintf(arrayIndexBuffer, "%s", (const char *)
	    arrayIndexStr.getCString());

	try
	{
	    _isValidIndex(arrayIndexBuffer);
            arrayIndex = atoi(arrayIndexBuffer);
	}
	catch (CIMException & c)
	{
	    arrayIndex = -1;

	    PEG_TRACE_STRING(TRC_IND_FORMATTER, Tracer::LEVEL4,c.getMessage());
	}
    }

    // Array index is out of range
    if (sizeOfArrayIndexStr != 0 &&
	((arrayIndex < 0) || ((Uint32)arrayIndex >= arraySize)))
    {
	arrayValues = "UNKNOWN";

        PEG_METHOD_EXIT();
        return (arrayValues);
    }

    switch (type)
    {
	case CIMTYPE_UINT8:
	{
	    Array<Uint8> propertyValueUint8;
	    propertyValue.get(propertyValueUint8);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer, "%u",
			propertyValueUint8[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer, "%u",
		    propertyValueUint8[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_UINT16:
	{
	    Array<Uint16> propertyValueUint16;
	    propertyValue.get(propertyValueUint16);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer, "%u",
			propertyValueUint16[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer, "%u",
		    propertyValueUint16[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_UINT32:
	{
	    Array<Uint32> propertyValueUint32;
	    propertyValue.get(propertyValueUint32);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer, "%u",
			propertyValueUint32[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer, "%u",
		    propertyValueUint32[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_UINT64:
	{
	    Array<Uint64> propertyValueUint64;
	    propertyValue.get(propertyValueUint64);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer,
			    "%" PEGASUS_64BIT_CONVERSION_WIDTH "u",
			    propertyValueUint64[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer,
			"%" PEGASUS_64BIT_CONVERSION_WIDTH "u",
		        propertyValueUint64[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_SINT8:
	{
	    Array<Sint8> propertyValueSint8;
	    propertyValue.get(propertyValueSint8);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer, "%i",
			propertyValueSint8[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer, "%i",
		    propertyValueSint8[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_SINT16:
	{
	    Array<Sint16> propertyValueSint16;
	    propertyValue.get(propertyValueSint16);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer, "%i",
			propertyValueSint16[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer, "%i",
		    propertyValueSint16[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_SINT32:
	{
	    Array<Sint32> propertyValueSint32;
	    propertyValue.get(propertyValueSint32);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer, "%i",
			propertyValueSint32[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer, "%i",
		    propertyValueSint32[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_SINT64:
	{
	    Array<Sint64> propertyValueSint64;
	    propertyValue.get(propertyValueSint64);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer,
                            "%" PEGASUS_64BIT_CONVERSION_WIDTH "d",
                            propertyValueSint64[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer,
			"%" PEGASUS_64BIT_CONVERSION_WIDTH "d",
                        propertyValueSint64[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_REAL32:
	{
	    Array<Real32> propertyValueReal32;
	    propertyValue.get(propertyValueReal32);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer, "%f",
			propertyValueReal32[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer, "%f",
		    propertyValueReal32[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_REAL64:
	{
	    Array<Real64> propertyValueReal64;
	    propertyValue.get(propertyValueReal64);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    sprintf(propertyValueBuffer, "%f",
			propertyValueReal64[i]);
		    arrayValues.append(propertyValueBuffer);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        sprintf(propertyValueBuffer, "%f",
		    propertyValueReal64[arrayIndex]);
	        arrayValues = propertyValueBuffer;
	    }

            break;
	}

	case CIMTYPE_BOOLEAN:
	{
	    Array<Boolean> booleanValue;
	    propertyValue.get(booleanValue);

	    Boolean canLocalize = false;

#if defined(PEGASUS_HAS_ICU) && defined(PEGASUS_INDFORMATTER_USE_ICU)
	    Locale locale;
	    canLocalize = _canLocalize(contentLangs, locale);
#endif

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
#if defined(PEGASUS_HAS_ICU) && defined(PEGASUS_INDFORMATTER_USE_ICU)
		    if (canLocalize)
		    {
			arrayValues.append(_localizeBooleanStr(
			    booleanValue[i], locale));
		    }
		    else
		    {
			arrayValues.append(_getBooleanStr(booleanValue[i]));
		    }
#else
		    arrayValues.append(_getBooleanStr(booleanValue[i]));

#endif
		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
#if defined(PEGASUS_HAS_ICU) && defined(PEGASUS_INDFORMATTER_USE_ICU)
                if (canLocalize)
		{
		    arrayValues = _localizeBooleanStr(
			booleanValue[arrayIndex], locale);
		}
		else
		{
		    arrayValues = _getBooleanStr(booleanValue[arrayIndex]);
		}
#else
		arrayValues = _getBooleanStr(booleanValue[arrayIndex]);
#endif
	    }

            break;
	}

	case CIMTYPE_CHAR16:
	{
	    Array<Char16> propertyValueChar16;
	    propertyValue.get(propertyValueChar16);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    arrayValues.append(propertyValueChar16[i]);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        arrayValues.append(propertyValueChar16[arrayIndex]);
	    }

            break;
	}

	case CIMTYPE_STRING:
	{
	    Array<String> propertyValueString;
	    propertyValue.get(propertyValueString);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    arrayValues.append(propertyValueString[i]);

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        arrayValues.append(propertyValueString[arrayIndex]);
	    }

            break;
	}

	case CIMTYPE_DATETIME:
	{
	    Array<CIMDateTime> propertyValueDateTime;
	    propertyValue.get(propertyValueDateTime);

            Boolean canLocalize = false;

#if defined(PEGASUS_HAS_ICU) && defined(PEGASUS_INDFORMATTER_USE_ICU)
	    Locale locale;
	    canLocalize = _canLocalize(contentLangs, locale);
#endif

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
#if defined(PEGASUS_HAS_ICU) && defined(PEGASUS_INDFORMATTER_USE_ICU)
                    if (canLocalize)
		    {
			arrayValues.append(_localizeDateTime(
			    propertyValueDateTime[i], locale));
		    }
		    else
		    {
		        arrayValues.append(propertyValueDateTime[i].toString());
		    }
#else
		    arrayValues.append(propertyValueDateTime[i].toString());
#endif

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
#if defined(PEGASUS_HAS_ICU) && defined(PEGASUS_INDFORMATTER_USE_ICU)
		if (canLocalize)
		{
		    arrayValues.append(_localizeDateTime(
			propertyValueDateTime[arrayIndex], locale));
		}
		else
		{
		    arrayValues.append(propertyValueDateTime
			[arrayIndex].toString());
		}
#else
	        arrayValues.append(propertyValueDateTime
		    [arrayIndex].toString());
#endif
	    }

            break;
	}

	case CIMTYPE_REFERENCE:
	{
	    Array<CIMObjectPath> propertyValueRef;
	    propertyValue.get(propertyValueRef);

	    // Empty brackets (e.g. []), gets all values of the array
	    if (sizeOfArrayIndexStr == 0)
	    {
                arrayValues.append("[");
		for (Uint32 i=0; i<arraySize; i++)
		{
		    arrayValues.append(propertyValueRef[i].toString());

		    if ( i < arraySize-1)
		    {
			arrayValues.append(",");
		    }
		}

		arrayValues.append("]");
	    }
	    else
	    {
	        arrayValues.append(propertyValueRef
		    [arrayIndex].toString());
	    }

            break;
	}

	default:
	{
	    arrayValues.append("UNKNOWN");

            PEG_TRACE_STRING(TRC_IND_FORMATTER, Tracer::LEVEL4,
		"Unknown CIMType: " + type);

            break;
	}
    }

    PEG_METHOD_EXIT();
    return (arrayValues);
}
Example #27
0
int main(int argc, char** argv) {
	if (argc < 7) {
		printf("Invalid input arguments\n");
		return -1;
	}
	unsigned int dev1 = 0, dev2 = 1, width = 0, height = 0, sizeThreshold = 0; // Width and height of the capture and minimun obj size
	sscanf(argv[1], "%d", &dev1);
	sscanf(argv[2], "%d", &dev2);
	sscanf(argv[3], "%d", &width);
	sscanf(argv[4], "%d", &height);
	sscanf(argv[5], "%d", &sizeThreshold);

	///
	namedWindow("Frames", CV_WINDOW_FREERATIO);
	setMouseCallback("Frames", onMouse, 0); // Callback for properly closing the app.

	///  CREATE SWITCH
	cvCreateTrackbar("Switch", "Frames", &switchButtonValue, 1,
			switch_callback);

	// OutputFile
	ofstream outFile[8];
	for (unsigned int i = 0; i < sizeof(uchar) * 8; i++) {
		String pathName;
		pathName = "outputs/outputFile";
		char ext[5] = { (char) (((int) '0') + i), '.', 't', 'x', 't' };
		pathName.append(ext);
		cout << pathName << endl;
		outFile[i].open(pathName.c_str());
	}
	ColorClusterSpace CS = *CreateHSVCS_8c(bin2dec("11111111"),
			bin2dec("11111111"), bin2dec(argv[6]));

	// Vector to organize RLEs
	static vector<vector<struct LineObjRLE> > aRLE1;
	static vector<vector<struct LineObjRLE> > aRLE2;

	// Vector of objects in the image.
	vector<SegmentedObject> objs1;
	vector<SegmentedObject> objs2;

	// Preparing ObjectMatching.
	StereoObjectMatching stereoMatching;


	// Preparando los filtros de Kalman
	Mat x0 = (Mat_<double>(6, 1) << 2, 2, 2, 0, 0, 0);

	// Extended Kalman filter applicated to Stereo Vision variables
	StereoVisionEKF EKFs[8] = { StereoVisionEKF(matQ, matR, x0),
			StereoVisionEKF(matQ, matR, x0), StereoVisionEKF(matQ, matR, x0),
			StereoVisionEKF(matQ, matR, x0), StereoVisionEKF(matQ, matR, x0),
			StereoVisionEKF(matQ, matR, x0), StereoVisionEKF(matQ, matR, x0),
			StereoVisionEKF(matQ, matR, x0) };

	camera cam1(alphaX, alphaY, gammaSkew, u0, v0, distortionMat,
			projectionMat);
	camera cam2(alphaX, alphaY, gammaSkew, u0, v0, distortionMat,
			projectionMat);

	// Time for EKF
	
	STime::init();

	STime *gTimer = STime::get();

	TReal *timers = new TReal[8];

	// Ref temp.
	TReal refTime0;
	TReal t1, t2;

	// Update timer.
	gTimer->update();

	// Get time for reference
	refTime0 = gTimer->frameTime();

	// Time reference for EKF filter
	for (unsigned int i = 0; i < sizeof(uchar) * 8; i++) {
		gTimer->update();
		timers[i] = gTimer->frameTime();
	}

	Mat frame1, frame2, ori1, ori2;
	InputDataManager idManager;
	waitKey();
	// loop
	while (waitKey(1) && exitFlag) {
		// MIRAR SI HEMOS CAMBIADO EL SWITCH
		if (!changeMethodDone) {
			if (switchButtonValue) {
				idManager.changeMethod(
						"/home/pablo/Desktop/Estimation/P1_640x480/Images/",
						"img%d_cam1.jpg", "img%d_cam2.jpg", width, height,
						"/home/pablo/Desktop/Estimation/P1_640x480/ViconData2.txt");
				changeMethodDone = true;
				CS = *CreateHSVCS_8c(bin2dec("11111111"), bin2dec("11111111"),
						bin2dec("00010000"));
				sizeThreshold = 20;
			} else {
				idManager.changeMethod(dev1, dev2, width, height);
				changeMethodDone = true;
				CS = *CreateHSVCS_8c(bin2dec("11111111"), bin2dec("11111111"),
						bin2dec("10000000"));
				sizeThreshold = 500;
			}
			// Get time for reference
			refTime0 = gTimer->frameTime();

			// Time reference for EKF filter
			for (unsigned int i = 0; i < sizeof(uchar) * 8; i++) {
				gTimer->update();
				timers[i] = gTimer->frameTime();
			}
		}
		//-------------------------------------

		gTimer->update();
		t1 = gTimer->frameTime();

		aRLE1.reserve(50000); // Need to be optimised
		aRLE2.reserve(50000); // Need to be optimised
		objs1.reserve(5000);
		objs2.reserve(5000);

		idManager.updateFrame();
		idManager.getFrames(frame1, frame2);

		frame1.copyTo(ori1);
		frame2.copyTo(ori2);

		medianBlur(frame1, frame1, 5);
		medianBlur(frame1, frame1, 5);
		medianBlur(frame2, frame2, 5);
		medianBlur(frame2, frame2, 5);

		imageBGR2HSV(frame1);
		imageBGR2HSV(frame2);

		segmentateImage(frame1, frame2, CS, objs1, aRLE1, objs2, aRLE2);

		//imshow("blurred", frame1);


		// Free memory
		aRLE1.clear();
		aRLE2.clear();

		// Update camera positions
		double incT;

		idManager.getNextCamPos(cam1, cam2, incT);

		// Update Matching object
		stereoMatching.compareAndUpdate(objs1,objs2);

		// EKFs
		for (unsigned int i = 0; i < sizeof(uchar) * 8; i++) {
			// EKF triangulation.
			trackedObject match1, match2;
			stereoMatching.getCurrentObjects(match1, match2, i);

			if (match1.flagUpdate && match2.flagUpdate) {
				Mat Zk =
					(Mat_<double>(4, 1) <<match1.mPos.x, match1.mPos.y, match2.mPos.x, match2.mPos.y);

				TReal auxTime;
				gTimer->update();
				auxTime = gTimer->frameTime();
				double diff = timers[i]-refTime0;

				if (incT == -1) {
					incT = diff;
				}

				timers[i] = auxTime;

				cout << "DIFERENCIA DE TIEMPO: " << diff << endl;
				cout << "Zk: {" << match1.mPos.x << ", " << match1.mPos.y
						<< ", " << match2.mPos.x << ", " << match2.mPos.x
						<< "} " << endl;

				EKFs[i].updateCameraPos(cam1.pos, cam2.pos,
						cam1.ori, cam2.ori);
				EKFs[i].updateIncT(diff);
				EKFs[i].stepEKF(Zk);

				Mat Xak;
				EKFs[i].getStateVector(Xak);

				double refTime = auxTime - refTime0;

				cout << "Time: " << refTime << endl << "State: " << Xak << endl;

				outFile[i] << refTime << " "
						<< Xak.ptr<double>(0)[0] << " " << Xak.ptr<double>(1)[0]
						<< " " << Xak.ptr<double>(2)[0] << endl;

			}
		}
		stereoMatching.setFlags(false);

		gTimer->update();
		t2 = gTimer->frameTime();
		double diff = t2-t1;
		cout << "FINISHED IN " << diff << endl;

		// Since here everything is for & about displaying information not real algorithm, so it's not included
		// in the time counter.
		imageHSV2BGR(frame1);
		imageHSV2BGR(frame2);

		highlighObjs(objs1, ori1, sizeThreshold);
		highlighObjs(objs2, ori2, sizeThreshold);

		hconcat(frame1, frame2, frame1);
		hconcat(ori1, ori2, ori1);
		vconcat(ori1, frame1, ori1);

		imshow("Frames", ori1);

		objs1.clear();
		objs2.clear();

		idManager.updateCurrentFrame();
	}

	aRLE1.clear();
	aRLE2.clear();
	objs1.clear();
	objs2.clear();

	STime::end();

}
void IndicationFormatter::_validatePropertyType (
    const CIMClass & indicationClass,
    const String & propertyParam,
    const String & typeStr,
    const Boolean & isArray)
{
    PEG_METHOD_ENTER (TRC_IND_FORMATTER,
	"IndicationFormatter::_validatePropertyType");

    String exceptionStr;
    char propertyTypeBuffer[32];
    char * providedPropertyType;
    Array <String> validPropertyTypes;

    String propertyTypeStr = typeStr;

    validPropertyTypes.append ( "boolean");
    validPropertyTypes.append ( "uint8");
    validPropertyTypes.append ( "sint8");
    validPropertyTypes.append ( "uint16");
    validPropertyTypes.append ( "sint16");
    validPropertyTypes.append ( "uint32");
    validPropertyTypes.append ( "sint32");
    validPropertyTypes.append ( "uint64");
    validPropertyTypes.append ( "sint64");
    validPropertyTypes.append ( "real32");
    validPropertyTypes.append ( "real64");
    validPropertyTypes.append ( "char16");
    validPropertyTypes.append ( "string");
    validPropertyTypes.append ( "datetime");
    validPropertyTypes.append ( "reference");

    propertyTypeStr.toLower();
    sprintf(propertyTypeBuffer, "%s",
        (const char *)propertyTypeStr.getCString());

    // skip white space
    providedPropertyType = propertyTypeBuffer;
    while (*providedPropertyType && isspace(*providedPropertyType))
    {
        providedPropertyType++;
    }

    String providedTypeStr = providedPropertyType;

    Uint32 space = providedTypeStr.find(" ");

    if (space != PEG_NOT_FOUND)
    {
	// skip the appended space from the providedTypeStr
	// e.g {1, string  }
	String restTypeStr = providedTypeStr.subString(space, PEG_NOT_FOUND);

        Uint32 i = 0;
        while (restTypeStr[i] == ' ')
        {
            i++;
        }

        restTypeStr = restTypeStr.subString(i, PEG_NOT_FOUND);
	if (strlen(restTypeStr.getCString()) == 0)
	{
	    providedTypeStr = providedTypeStr.subString(0, space);
	}
        else
        {
            // the provided property type is not a valid type
            // e.g. {1, string  xxx}
            MessageLoaderParms parms(
                "IndicationFormatter.IndicationFormatter._MSG_INVALID_TYPE_OF_FOR_PROPERTY",
            "Invalid property type of $0 in property $1",
            providedPropertyType,
            _PROPERTY_TEXTFORMAT.getString());
        } 
    }

    //
    // Checks if the provided property type is a valid type
    //
    if (!(Contains (validPropertyTypes, providedTypeStr)))
    {
	// the provided property type is not valid type
	MessageLoaderParms parms(
	"IndicationFormatter.IndicationFormatter._MSG_INVALID_TYPE_OF_FOR_PROPERTY",
	"Invalid property type of $0 in property $1",
	providedPropertyType,
	_PROPERTY_TEXTFORMAT.getString());

	exceptionStr.append(MessageLoader::getMessage(parms));

	PEG_METHOD_EXIT();
	throw PEGASUS_CIM_EXCEPTION (
	    CIM_ERR_INVALID_PARAMETER, exceptionStr);
    }

    for (Uint32 i = 0; i < indicationClass.getPropertyCount (); i++)
    {
	CIMName propertyName = indicationClass.getProperty (i).getName ();

        if (String::equalNoCase(propertyParam, (propertyName.getString())))
        {
	    // get the property type;
	    CIMType propertyType =
	                indicationClass.getProperty (i).getType();

	    // Check if the property is an array type
	    if ((isArray && !(indicationClass.getProperty(i).isArray())) ||
		(!isArray && indicationClass.getProperty(i).isArray()))
	    {
		MessageLoaderParms parms(
		"IndicationFormatter.IndicationFormatter._MSG_PROPERTY_IS_NOT_AN_ARRAY_TYPE",
		"The property $0 is not an array type",
                propertyName.getString());

	        exceptionStr.append(MessageLoader::getMessage(parms));

	        PEG_METHOD_EXIT();
	        throw PEGASUS_CIM_EXCEPTION (
	            CIM_ERR_INVALID_PARAMETER, exceptionStr);
	    }

	    // property type matchs
            if (String::equalNoCase(providedTypeStr,
	        cimTypeToString(propertyType)))
            {
	        break;
	    }
	    else
	    {
	        MessageLoaderParms parms(
	        "IndicationFormatter.IndicationFormatter._MSG_MISS_MATCHED_TYPE_OF_FOR_PROPERTY",
	        "The provided property type of $0 in $1 does not match the property type $2",
	         providedPropertyType,
		cimTypeToString(propertyType),
	        _PROPERTY_TEXTFORMAT.getString());

	        exceptionStr.append(MessageLoader::getMessage(parms));

	        PEG_METHOD_EXIT();
	        throw PEGASUS_CIM_EXCEPTION (
	            CIM_ERR_INVALID_PARAMETER, exceptionStr);
            }

        }
    }

    PEG_METHOD_EXIT();
}
int main(int argc, char** argv)
{
    verbose = (getenv ("PEGASUS_TEST_VERBOSE")) ? true : false;
    if (verbose) cout << argv[0] << ": started" << endl;

#if defined(PEGASUS_OS_TYPE_UNIX)

    try
    {
#ifdef DEBUG
        Tracer::setTraceFile("./Authentication.trc");
        Tracer::setTraceComponents("all");
        Tracer::setTraceLevel(Tracer::LEVEL4);
	verbose = true;
#endif

        ConfigManager* configManager = ConfigManager::getInstance();

        const char* path = getenv("PEGASUS_HOME");
        String pegHome = path;

        if(pegHome.size())
            ConfigManager::setPegasusHome(pegHome);

        if (verbose) cout << "Peg Home : " << ConfigManager::getPegasusHome() << endl;

        if (verbose) cout << "Doing testAuthHeader()...." << endl;

        // -- Create a test repository:

        const char* tmpDir = getenv ("PEGASUS_TMP");
        String repositoryPath;
        if (tmpDir == NULL)
        {
            repositoryPath = ".";
        }
        else
        {
            repositoryPath = tmpDir;
        }
        repositoryPath.append("/repository");

        PEGASUS_ASSERT(FileSystem::isDirectory(repositoryPath));

        CIMRepository* repository = new CIMRepository(repositoryPath);

        // -- Create a UserManager object:

        UserManager* userManager = UserManager::getInstance(repository);

        testAuthHeader();

        if (verbose) cout << "Doing testAuthenticationFailure_1()...." << endl;
        testAuthenticationFailure_1();

        if (verbose) cout << "Doing testAuthenticationFailure_2()...." << endl;
        testAuthenticationFailure_2();

        if (verbose) cout << "Doing testAuthenticationFailure_3()...." << endl;
        testAuthenticationFailure_3();

        if (verbose) cout << "Doing testAuthenticationFailure_4()...." << endl;
        testAuthenticationFailure_4();

        if (verbose) cout << "Doing testAuthenticationSuccess()...." << endl;
        testAuthenticationSuccess();
    }
    catch(Exception& e)
    {
      cout << argv[0] << " Exception: " << e.getMessage() << endl;
        PEGASUS_ASSERT(0);
    }

#endif

    cout << argv[0] << " +++++ passed all tests" << endl;

    return 0;
}
Example #30
0
String CookieManager::generateHtmlFragmentForCookies()
{
    // If the database hasn't been sync-ed at this point, force a sync load
    if (!m_syncedWithDatabase && !m_privateMode)
        m_cookieBackingStore->openAndLoadDatabaseSynchronously(cookieJar());

    CookieLog("CookieManager - generateHtmlFragmentForCookies\n");

    Vector<RefPtr<ParsedCookie> > cookieCandidates;
    for (HashMap<String, CookieMap*>::iterator it = m_managerMap.begin(); it != m_managerMap.end(); ++it)
        it->value->getAllChildCookies(&cookieCandidates);

    String result;
    RefPtr<ParsedCookie> cookie = 0;
    result.append(String("<table style=\"word-wrap:break-word\" cellSpacing=\"0\" cellPadding=\"0\" border=\"1\"><tr><th>Domain</th><th>Path</th><th>Protocol</th><th>Name</th><th>Value</th><th>Secure</th><th>HttpOnly</th><th>Session</th></tr>"));
    for (size_t i = 0; i < cookieCandidates.size(); ++i) {
        cookie = cookieCandidates[i];
        result.append(String("<tr><td align=\"center\">"));
        result.append(cookie->domain());
        result.append(String("<td align=\"center\">"));
        result.append(cookie->path());
        result.append(String("<td align=\"center\">"));
        result.append(cookie->protocol());
        result.append(String("<td align=\"center\">"));
        result.append(cookie->name());
        result.append(String("<td align=\"center\" style= \"word-break:break-all\">"));
        result.append(cookie->value());
        result.append(String("<td align=\"center\">"));
        result.append(String(cookie->isSecure() ? "Yes" : "No"));
        result.append(String("<td align=\"center\">"));
        result.append(String(cookie->isHttpOnly() ? "Yes" : "No"));
        result.append(String("<td align=\"center\">"));
        result.append(String(cookie->isSession() ? "Yes" : "No"));
        result.append(String("</td></tr>"));
    }
    result.append(String("</table>"));
    return result;
}