コード例 #1
0
ファイル: creddy.c プロジェクト: nbsdx/abac
int main(int argc, char **argv) {
    options_t options = { 0, };
    char *validity_str = NULL;

    libabac_init();

    subjects = xmalloc(sizeof(subject_t) * 2);
    subjects_size = 2;

    roles = xmalloc(sizeof(char *) * 2);
    roles_size = 2;

    struct option getopts[] = {
        { "help",       0, &options.help, 1 },
        { "generate",   0, &options.mode, MODE_GENERATE },
        { "verify",     0, &options.mode, MODE_VERIFY },
        { "keyid",      0, &options.mode, MODE_KEYID },
        { "attribute",  0, &options.mode, MODE_ATTRIBUTE },
        { "roles",      0, &options.mode, MODE_ROLES },
        { "version",    0, &options.mode, MODE_VERSION },
        { "display",    0, &options.mode, MODE_DISPLAY },

        { "cert",       1, 0, OPT_CERT },

        // generate options
        { "cn",         1, 0, OPT_CN },
        { "validity",   1, 0, OPT_VALIDITY },

        // attribute options
        { "issuer",     1, 0, OPT_ISSUER },
        { "key",        1, 0, OPT_KEY },
        { "role",       1, 0, OPT_ROLE },
        { "subject-cert", 1, 0, OPT_SUBJECT_CERT },
        { "subject-id", 1, 0, OPT_SUBJECT_ID },
        { "subject-role", 1, 0, OPT_SUBJECT_ROLE },
        { "out",          1, 0, OPT_OUT },

        // attribute_rule option
        { "attrrule",   1, 0, OPT_ATTRRULE },

        // verify option
        { "attrcert",   1, 0, OPT_ATTRCERT },

        // display options
        { "show",       1, 0, OPT_SHOW },

        { NULL },
    };

    for ( ; ; ) {
        int c = getopt_long(argc, argv, "", getopts, NULL);
        if (c < 0)
            break;

        switch (c) {
            // set the option from the value in the getopts struct
            case 0:
                continue;

            case OPT_CERT:
                options.cert = xstrdup(optarg);
                break;

            // generate options
            case OPT_CN:
                options.cn = xstrdup(optarg);
                break;
            case OPT_VALIDITY: // also an attribute option
                validity_str = xstrdup(optarg);
                break;

            // attribute options
            case OPT_ISSUER:
                options.issuer = xstrdup(optarg);
                break;
            case OPT_KEY: // also an generate option
                options.key = xstrdup(optarg);
                break;
            case OPT_ROLE:
                options.role = xstrdup(optarg);
                break;
            case OPT_SUBJECT_CERT:
                subject(xstrdup(optarg), 1);
                break;
            case OPT_SUBJECT_ID:
                subject(xstrdup(optarg), 0);
                break;
            case OPT_SUBJECT_ROLE:
                role(xstrdup(optarg));
                break;
            case OPT_OUT:
                options.out = xstrdup(optarg);
                break;

            // attribute rule options
            case OPT_ATTRRULE:
                options.attrrule = xstrdup(optarg);
                break;

            // verify options
            case OPT_ATTRCERT:
                options.attrcert = xstrdup(optarg);
                break;

            // display options
            case OPT_SHOW:
                options.show = xstrdup(optarg);
                break;

            case '?':
                break;

            default:
                printf("wat\n");
                return 45;
        }
    }

    if (options.help || optind < argc) {
        if (optind > 0 && optind < argc)
            printf("I don't understand %s\n", argv[optind]);
        usage(&options);
    }

    // parse the validity
    if (validity_str != NULL) {
        char suffix = 'd'; // default suffix is days
        int multiplier;

        int len = strlen(validity_str);
        assert(len > 0);

        // get the suffix char if it's alphabetical
        if (isalpha(validity_str[len - 1])) {
            suffix = validity_str[len - 1];

            // truncate
            validity_str[len - 1] = '\0';
            --len;

            // make sure it's not only a suffix
            if (len == 0) {
                printf("Invalid validity\n");
                usage(&options);
            }
        }

        // convert the suffix to a multiplier
        switch(suffix) {
            case 's': multiplier =        1; break;
            case 'm': multiplier =       60; break;
            case 'h': multiplier =     3600; break;
            case 'd': multiplier =    86400; break;
            case 'y': multiplier = 31536000; break;
            default:
                printf("Invalid suffix, must be s m h d y\n");
                usage(&options);
        }

        // ascii to int
        char *end;
        options.validity = strtol(validity_str, &end, 10);
        if (errno != 0 || end - validity_str < len) {
            printf("Invalid validity\n");
            usage(&options);
        }

        if (options.validity <= 0) {
            printf("Invalid validity: must be > 0\n");
            usage(&options);
        }

        // multiply!
        options.validity *= multiplier;

        free(validity_str);
    }

    if (options.mode == MODE_ATTRIBUTE && options.attrrule == NULL) {
        int i;

        // have to do error checking on subjects here
        if (
                (num_subjects == 0) ||
                (num_subjects != num_roles && num_subjects != 1 && num_roles != 0)
           ) {
            printf(
                "You have %d subject%s and %d role%s, which is invalid\n",
                num_subjects, num_subjects == 1 ? "" : "s",
                num_roles, num_roles == 1 ? "" : "s"
            );
            usage(&options);
        }

        for (i = 0; i < num_roles; ++i)
            subjects[i].role = roles[i];
        free(roles);

        options.subjects = subjects;
        options.num_subjects = num_subjects;
    }

    // launch the sub command
    switch (options.mode) {
        case MODE_GENERATE:
            if (options.validity == 0) options.validity = 1080 * 86400;
            generate_main(&options);
            break;

        case MODE_KEYID:
            keyid_main(&options);
            break;

        case MODE_ATTRIBUTE:
            if (options.validity == 0) options.validity = 365 * 86400;
            if(options.attrrule)
                attribute_rule_main(&options);
                else attribute_main(&options);
            break;

        case MODE_ROLES:
            roles_main(&options);
            break;

        case MODE_VERIFY:
            verify_main(&options);
            break;

        case MODE_DISPLAY:
            display_main(&options);
            break;

        case MODE_VERSION:
            printf("ABAC/creddy " ABAC_VERSION "\n");
            break;

        default:
            usage(&options);
    }

    return 0;
}
コード例 #2
0
void MessageSender::send()
{
//! [associate-account]
    QString accountName(accountCombo->currentText());
    if (accountName.isEmpty()) {
        QMessageBox::warning(0, tr("Missing information"), tr("No account is selected for transmission"));
        return;
    }

    QMessage message;

    QPair<QMessage::Type, QMessageAccountId> details = accountDetails[accountName];
    message.setType(details.first);
    message.setParentAccountId(details.second);
//! [associate-account]

//! [set-recipients]
    QString to(toEdit->text());
    if (to.isEmpty()) {
        QMessageBox::warning(0, tr("Missing information"), tr("Please enter a recipient address"));
        return;
    }

    // Find the address type to use for this message
    QMessageAddress::Type addrType(message.type() == QMessage::Email ? QMessageAddress::Email : QMessageAddress::Phone);

    QMessageAddressList toList;
    foreach (const QString &item, to.split(QRegExp("\\s"), QString::SkipEmptyParts)) {
        toList.append(QMessageAddress(addrType, item));
    }
    message.setTo(toList);
//! [set-recipients]

//! [set-properties]
    if (message.type() == QMessage::Email) {
        QString subject(subjectEdit->text());
        if (subject.isEmpty()) {
            QMessageBox::warning(0, tr("Missing information"), tr("Please enter a subject"));
            return;
        }
        message.setSubject(subject);
    }

    QString text(textEdit->toPlainText());
    if (text.isEmpty()) {
        QMessageBox::warning(0, tr("Missing information"), tr("Please enter a message"));
        return;
    }
    message.setBody(text);
//! [set-properties]

//! [add-attachments]
    if (message.type() != QMessage::Sms) {
        if (attachmentsList->count()) {
            QStringList paths;
            for (int i = 0; i < attachmentsList->count(); ++i) {
                paths.append(attachmentsList->item(i)->text());
            }

            message.appendAttachments(paths);
        }
    }
//! [add-attachments]

//! [send-message]
    sendButton->setEnabled(false);
    if (service.send(message)) {
        sendId = message.id();
    } else {
        sendButton->setEnabled(true);
        QMessageBox::warning(0, tr("Failed"), tr("Unable to send message"));
    }
//! [send-message]
}
コード例 #3
0
void VendorDataComponent::runVendorUpdate() {
	ManagedReference<SceneObject*> strongParent = parent.get();

	if (strongParent == NULL || strongParent->getZoneServer() == NULL)
		return;

	ManagedReference<CreatureObject*> owner = strongParent->getZoneServer()->getObject(getOwnerId()).castTo<CreatureObject*>();
	ManagedReference<PlayerManager*> playerManager = strongParent->getZoneServer()->getPlayerManager();
	ManagedReference<TangibleObject*> vendor = cast<TangibleObject*>(strongParent.get());

	if (owner == NULL || !owner->isPlayerCreature() || playerManager == NULL || vendor == NULL) {
		return;
	}

	scheduleVendorCheckTask(VENDORCHECKINTERVAL);

	removeAllVendorBarks();

	int now = time(0);
	int last = lastSuccessfulUpdate.getTime();
	float hoursSinceLastUpdate = now - last;
	hoursSinceLastUpdate /= 3600.f;

	if (maintAmount > 0)
		inactiveTimer.updateToCurrentTime();

	/// parent salaries
	Locker vlocker(owner, vendor);
	maintAmount -= getMaintenanceRate() * hoursSinceLastUpdate;

	if (maintAmount < 0) {
		vendor->setConditionDamage(-maintAmount, true);
	} else {
		vendor->setConditionDamage(0, true);
		vendor->setMaxCondition(1000, true);
	}

	if (isEmpty()) {
		ManagedReference<ChatManager*> cman = strongParent->getZoneServer()->getChatManager();

		String sender = strongParent->getDisplayedName();
		UnicodeString subject("@auction:vendor_status_subject");

		if (!mail1Sent && time(0) - emptyTimer.getTime() > FIRSTWARNING) {
			StringIdChatParameter body("@auction:vendor_status_unaccessed");
			body.setTO(strongParent->getDisplayedName());
			if (cman != NULL)
				cman->sendMail(sender, subject, body, owner->getFirstName());
			mail1Sent = true;
		}

		else if (!mail2Sent && time(0) - emptyTimer.getTime() > SECONDWARNING) {
			StringIdChatParameter body("@auction:vendor_status_endangered");
			body.setTO(strongParent->getDisplayedName());
			if (cman != NULL)
				cman->sendMail(sender, subject, body, owner->getFirstName());
			mail2Sent = true;
		}

		else if (time(0) - emptyTimer.getTime() > EMPTYDELETE) {
			StringIdChatParameter body("@auction:vendor_status_deleted");
			if (cman != NULL)
				cman->sendMail(sender, subject, body, owner->getFirstName());
			VendorManager::instance()->destroyVendor(vendor);
			vendorCheckTask->cancel();
			return;
		}

	} else {
		mail1Sent = false;
		mail2Sent = false;
		emptyTimer.updateToCurrentTime();
	}

	if (isOnStrike()) {
		if (isRegistered())
			VendorManager::instance()->handleUnregisterVendor(owner, vendor);

		if (isVendorSearchEnabled())
			setVendorSearchEnabled(false);

		if (time(0) - inactiveTimer.getTime() > DELETEWARNING) {

			ManagedReference<ChatManager*> cman = strongParent->getZoneServer()->getChatManager();

			String sender = strongParent->getDisplayedName();
			UnicodeString subject("@auction:vendor_status_subject");

			StringIdChatParameter body("@auction:vendor_status_deleted");
			if (cman != NULL)
				cman->sendMail(sender, subject, body, owner->getFirstName());
			VendorManager::instance()->destroyVendor(vendor);
			vendorCheckTask->cancel();
		}

	} else {

		/// Award hourly XP
		assert(vendor->isLockedByCurrentThread());

		Locker locker(owner, vendor);
		playerManager->awardExperience(owner, "merchant", 150 * hoursSinceLastUpdate, false);

		playerManager->awardExperience(owner, "merchant", awardUsageXP * 50, false);

	}

	awardUsageXP = 0;
	lastSuccessfulUpdate.updateToCurrentTime();
}
コード例 #4
0
int main(int argc, char ** argv)
{
	setlocale(LC_MESSAGES, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);

	try
	{
		enum
		{
			rdf_ntriple,
			rdf_turtle,
			vorbis_comments,
			metadata_author,
			metadata_creation,
			metadata_description,
			metadata_language,
			metadata_modification,
			metadata_publication,
			metadata_publisher,
			metadata_rights,
			metadata_subjects,
			metadata_title,
		} output_type = rdf_ntriple;

		bool print_time = false;
		bool all_metadata = false;

		const option_group general_options = { nullptr, {
			{ 't', "time", bind_value(print_time, true),
			  i18n("Time how long it takes to extract the metadata") },
			{ 'a', "all", bind_value(all_metadata, true),
			  i18n("Extract all available metadata") },
		}};

		const option_group format_options = { i18n("Metadata Format:"), {
			{ 0, "ntriple", bind_value(output_type, rdf_ntriple),
			  i18n("Output RDF N-Triple metadata statements") },
			{ 0, "turtle", bind_value(output_type, rdf_turtle),
			  i18n("Output RDF Turtle metadata statements") },
			{ 0, "vorbis", bind_value(output_type, vorbis_comments),
			  i18n("Output VorbisComment entries") },
		}};

		const option_group extract_options = { i18n("Metadata Extraction:"), {
			{ 0, "author", bind_value(output_type, metadata_author),
			  i18n("Output the document author") },
			{ 0, "creation", bind_value(output_type, metadata_creation),
			  i18n("Output the document creation date") },
			{ 0, "description", bind_value(output_type, metadata_description),
			  i18n("Output the document description") },
			{ 0, "language", bind_value(output_type, metadata_language),
			  i18n("Output the document language") },
			{ 0, "modification", bind_value(output_type, metadata_modification),
			  i18n("Output the document modification date") },
			{ 0, "publication", bind_value(output_type, metadata_publication),
			  i18n("Output the document publication date") },
			{ 0, "publisher", bind_value(output_type, metadata_publisher),
			  i18n("Output the document publisher") },
			{ 0, "rights", bind_value(output_type, metadata_rights),
			  i18n("Output the document rights (e.g. copyright)") },
			{ 0, "subjects", bind_value(output_type, metadata_subjects),
			  i18n("Output the document subjects") },
			{ 0, "title", bind_value(output_type, metadata_title),
			  i18n("Output the document title") },
		}};

		const std::initializer_list<const option_group *> options = {
			&general_options,
			&format_options,
			&extract_options,
		};

		const std::initializer_list<const char *> usage = {
			i18n("metadata [OPTION..] DOCUMENT.."),
		};

		if (!parse_command_line(options, usage, argc, argv))
			return 0;

		cainteoir::stopwatch timer;
		rdf::graph metadata;

		if (argc == 0)
			cainteoir::createDocumentReader(nullptr, metadata, std::string());
		else for(int i = 0; i < argc; ++i)
		{
			auto reader = cainteoir::createDocumentReader(argv[i], metadata, std::string());
			if (!reader)
				fprintf(stderr, i18n("unsupported document format for file \"%s\"\n"), argv[i]);
			if (all_metadata)
				while (reader->read(&metadata)) ;
		}

		if (print_time)
			fprintf(stderr, "Extraction Time: %G\n", timer.elapsed());

		const char *filename = (argc == 1) ? argv[0] : nullptr;
		rdf::uri subject(filename ? filename : std::string(), std::string());

		if (!metadata.empty()) switch (output_type)
		{
		case vorbis_comments:
			{
				const rdf::uri subject = rdf::uri(argv[0], std::string());
				std::list<cainteoir::vorbis_comment> comments;
				cainteoir::add_document_metadata(comments, metadata, subject);
				for (auto &comment : comments)
					std::cout << comment.label << "=" << comment.value << std::endl;
			}
			break;
		case metadata_author:
			fprintf(stdout, "%s\n", get_author(metadata, subject).c_str());
			break;
		case metadata_creation:
			fprintf(stdout, "%s\n", get_date(metadata, subject, "creation").c_str());
			break;
		case metadata_description:
			fprintf(stdout, "%s\n", get_dublincore(metadata, subject, "description").c_str());
			break;
		case metadata_language:
			fprintf(stdout, "%s\n", get_dublincore(metadata, subject, "language").c_str());
			break;
		case metadata_modification:
			fprintf(stdout, "%s\n", get_date(metadata, subject, "modification").c_str());
			break;
		case metadata_publication:
			fprintf(stdout, "%s\n", get_date(metadata, subject, "publication").c_str());
			break;
		case metadata_publisher:
			fprintf(stdout, "%s\n", get_dublincore(metadata, subject, "publisher").c_str());
			break;
		case metadata_rights:
			fprintf(stdout, "%s\n", get_dublincore(metadata, subject, "rights").c_str());
			break;
		case metadata_subjects:
			for (auto &item : get_dublincore_items(metadata, subject, "subject"))
				fprintf(stdout, "%s\n", item.c_str());
			break;
		case metadata_title:
			fprintf(stdout, "%s\n", get_dublincore(metadata, subject, "title").c_str());
			break;
		default:
			{
				(*rdf::create_formatter(std::cout, output_type == rdf_ntriple ? rdf::formatter::ntriple : rdf::formatter::turtle))
					<< rdf::rdf
					<< rdf::rdfa
					<< rdf::rdfs
					<< rdf::xsd
					<< rdf::xml
					<< rdf::owl
					<< rdf::dc
					<< rdf::dcterms
					<< rdf::dcam
					<< rdf::epub
					<< rdf::epv
					<< rdf::opf
					<< rdf::ocf
					<< rdf::pkg
					<< rdf::media
					<< rdf::onix
					<< rdf::marc
					<< rdf::ncx
					<< rdf::dtb
					<< rdf::smil
					<< rdf::xhtml
					<< rdf::skos
					<< rdf::foaf
					<< rdf::ref
					<< rdf::tts
					<< rdf::iana
					<< rdf::subtag
					<< metadata;
			}
			break;
		}
	}
	catch (std::runtime_error &e)
	{
		fprintf(stderr, i18n("error: %s\n"), e.what());
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
コード例 #5
0
const std::string ShowPendingMessagePage::GenerateContent(const std::string &method, const std::map<std::string,QueryVar> &queryvars)
{
	if(queryvars.find("formaction")!=queryvars.end() && (*queryvars.find("formaction")).second=="delete" && ValidateFormPassword(queryvars))
	{
		m_log->information("User requested to delete message "+(*queryvars.find("uuid")).second.GetData());
		SQLite3DB::Statement st=m_db->Prepare("DELETE FROM tblMessageInserts WHERE MessageUUID=?");
		st.Bind(0, (*queryvars.find("uuid")).second.GetData());
		st.Step();
	}

	SQLite3DB::Statement st=m_db->Prepare("SELECT LocalIdentityID, MessageXML, SendDate, MessageUUID FROM tblMessageInserts WHERE Inserted='false';");
	st.Step();
	int msgcount=0;
	std::string tblcontent="";
	std::string content="";
	tblcontent+="<table><tr><td>"+m_trans->Get("web.page.pendingmessages.identity")+"</td><td>"+m_trans->Get("web.page.pendingmessages.boards")+"</td><td>"+m_trans->Get("web.page.pendingmessages.subject")+"</td><td>"+m_trans->Get("web.page.pendingmessages.time")+"</td></tr>";
	while (st.RowReturned())
	{	
		int identityid=0;
		std::string time("");
		std::string uuid("");
		std::string subject("");

		st.ResultInt(0,identityid);
		st.ResultText(2,time);
		st.ResultText(3, uuid);

		LocalIdentity ident(m_db); //found a canned way, thanks SomeDude!
		ident.Load(identityid);

		tblcontent+="<tr><td>";
		tblcontent+=SanitizeOutput(ident.GetName())+"</td><td>";
		//yes, the next bit sucks but there's no better way to do it (that I could find)
		//we will look at the message XML to find the board(s) posted to.... 
		std::string xml="";
		st.ResultText(1,xml);
		MessageXML mxml;
		mxml.ParseXML(xml);
		std::vector<std::string> boards=mxml.GetBoards();
		std::vector<std::string>::iterator iter;
		for (iter=boards.begin(); iter!=boards.end(); ++iter) tblcontent+=*iter+", ";
		tblcontent.erase(tblcontent.length()-2); //strip final ", "
		tblcontent+="</td><td>";
		subject=mxml.GetSubject();
		tblcontent+=SanitizeOutput(subject);
		tblcontent+="</td><td>";
		tblcontent+=time+"</td><td>";
		//button
		tblcontent+="<form name=\"frmdelete\" method=\"POST\">";
		tblcontent+=CreateFormPassword();
		tblcontent+="<input type=\"hidden\" name=\"formaction\" value=\"delete\">";
		tblcontent+="<input type=\"hidden\" name=\"uuid\" value=\""+uuid+"\">";
		tblcontent+="<input type=\"submit\" value=\""+m_trans->Get("web.page.pendingmessages.deletemessage")+"\">";
		tblcontent+="</form>";
		tblcontent+="</td></tr>";
		st.Step();
		msgcount++;
	}
	tblcontent+="</table>";

	std::string msgcountstr("");
	StringFunctions::Convert(msgcount,msgcountstr);
	content="<h2>"+msgcountstr+" "+m_trans->Get("web.page.pendingmessages.messageswaiting")+"</h2>";

	content+=tblcontent;

	return content;
}
コード例 #6
0
ファイル: read.c プロジェクト: bencrox/hkday-pttbbs
/**
 * 根據 stypen 選擇上/下一篇文章
 *
 * @param locmem  用來存在某看板游標位置的 structure。
 * @param stypen  游標移動的方法
 *           CURSOR_FIRST, CURSOR_NEXT, CURSOR_PREV:
 *             與游標目前位置的文章同標題 的 第一篇/下一篇/前一篇 文章。
 *           RELATE_FIRST, RELATE_NEXT, RELATE_PREV:
 *             與目前正閱讀的文章同標題 的 第一篇/下一篇/前一篇 文章。
 *           NEWPOST_NEXT, NEWPOST_PREV:
 *             下一個/前一個 thread 的第一篇。
 *           AUTHOR_NEXT, AUTHOR_PREV:
 *             XXX 這功能目前好像沒用到?
 *
 * @return 新的游標位置
 */
static int
thread(const keeploc_t * locmem, int stypen)
{
    fileheader_t fh;
    int     pos = locmem->crs_ln, jump = THREAD_SEARCH_RANGE, new_ln;
    int     fd = -1, amatch = -1;
    int     step = (stypen & RS_FORWARD) ? 1 : -1;
    const char *key;

    if(locmem->crs_ln==0)
        return locmem->crs_ln;

    STATINC(STAT_THREAD);
    if (stypen & RS_AUTHOR)
        key = headers[pos - locmem->top_ln].owner;
    else if (stypen & RS_CURRENT)
        key = subject(currtitle);
    else
        key = subject(headers[pos - locmem->top_ln].title );

    for( new_ln = pos + step ;
            new_ln > 0 && new_ln <= last_line && --jump > 0;
            new_ln += step ) {

        int rk =
            get_record_keep(currdirect, &fh, sizeof(fileheader_t), new_ln, &fd);

        if(fd < 0 || rk < 0)
        {
            new_ln = pos;
            break;
        }

        if( stypen & RS_TITLE ) {
            if( stypen & RS_FIRST ) {
                if( !strncmp(fh.title, key, PROPER_TITLE_LEN) )
                    break;
                else if( !strncmp(&fh.title[4], key, PROPER_TITLE_LEN) ) {
                    amatch = new_ln;
                    jump = THREAD_SEARCH_RANGE;
                    /* 當搜尋同主題第一篇, 連續找不到多少篇才停 */
                }
            }
            else if( !strncmp(subject(fh.title), key, PROPER_TITLE_LEN) )
                break;
        }
        else if( stypen & RS_NEWPOST ) {
            if( strncmp(fh.title, "Re:", 3) )
                break;
        }
        else { // RS_AUTHOR
            if( strcmp(subject(fh.owner), key) == EQUSTR )
                break;
        }
    }

    if( fd != -1 )
        close(fd);

    if( jump <= 0 || new_ln <= 0 || new_ln > last_line )
        new_ln = (amatch == -1 ? pos : amatch); //didn't find

    return new_ln;
}
コード例 #7
0
void NewsArticle::assemble()
{
    Headers::Base *h;
    QCString newHead = "";

    //Message-ID
    if((h = messageID(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Control
    if((h = control(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Supersedes
    if((h = supersedes(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //From
    h = from(); // "From" is mandatory
    newHead += h->as7BitString() + "\n";

    //Subject
    h = subject(); // "Subject" is mandatory
    newHead += h->as7BitString() + "\n";

    //To
    if((h = to(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Newsgroups
    if((h = newsgroups(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Followup-To
    if((h = followUpTo(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Reply-To
    if((h = replyTo(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Mail-Copies-To
    if((h = mailCopiesTo(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Date
    h = date(); // "Date" is mandatory
    newHead += h->as7BitString() + "\n";

    //References
    if((h = references(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Lines
    h = lines(); // "Lines" is mandatory
    newHead += h->as7BitString() + "\n";

    //Organization
    if((h = organization(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //User-Agent
    if((h = userAgent(false)) != 0)
        newHead += h->as7BitString() + "\n";

    //Mime-Version
    newHead += "MIME-Version: 1.0\n";

    //Content-Type
    newHead += contentType()->as7BitString() + "\n";

    //Content-Transfer-Encoding
    newHead += contentTransferEncoding()->as7BitString() + "\n";

    //X-Headers
    int pos = h_ead.find("\nX-");
    if(pos > -1) //we already have some x-headers => "recycle" them
        newHead += h_ead.mid(pos + 1, h_ead.length() - pos);
    else if(h_eaders && !h_eaders->isEmpty())
    {
        for(h = h_eaders->first(); h; h = h_eaders->next())
        {
            if(h->isXHeader() && (strncasecmp(h->type(), "X-KNode", 7) != 0))
                newHead += h->as7BitString() + "\n";
        }
    }

    h_ead = newHead;
}
コード例 #8
0
GLC_Vector2d round(const GLC_Vector2d& vector)
{
	GLC_Vector2d subject(glc::round(vector.getX()), glc::round(vector.getY()));

	return subject;
}
コード例 #9
0
GLC_Vector3d round(const GLC_Vector3d& vector)
{
	GLC_Vector3d subject(glc::round(vector.x()), glc::round(vector.y()), glc::round(vector.z()));

	return subject;
}
コード例 #10
0
QPointF glc::round(const QPointF& point)
{
	QPointF subject(glc::round(static_cast<double>(point.x())), glc::round(static_cast<double>(point.y())));
	return subject;
}
コード例 #11
0
int main(int argc, char** argv)
{
  try
  {
    std::wstring modelURL
      (L"http://models.cellml.org/workspace/hodgkin_huxley_1952/@@rawfile/949cd4d3/hodgkin_huxley_1952.cellml");

    // Create a CellML Bootstrap and a model loader.
    ObjRef<iface::cellml_api::CellMLBootstrap> bootstrap(CreateCellMLBootstrap());
    ObjRef<iface::cellml_api::DOMModelLoader> loader(bootstrap->modelLoader());
    
    // Load a CellML model.
    ObjRef<iface::cellml_api::Model> hhModel
      (loader->loadFromURL(modelURL));
    
    // Request a RDF/API capable RDF representation...
    ObjRef<iface::cellml_api::RDFRepresentation> rr(hhModel->getRDFRepresentation(L"http://www.cellml.org/RDF/API"));
    ObjRef<iface::rdf_api::RDFAPIRepresentation> rrHH(QueryInterface(rr));

    // Retrieve the DataSource. Note: Changes to the data source are not pushed back
    // to the model until the source attribute is set on the rrHH again.
    ObjRef<iface::rdf_api::DataSource> dsHH(rrHH->source());

    // Get the resource corresponding to the cmeta:id on the model. Note that
    // cmetaId can return the empty string, which you should check for in
    // production code, if there is no cmeta:id
    ObjRef<iface::rdf_api::URIReference> hhModelRef
      (dsHH->getURIReference(bootstrap->makeURLAbsolute(modelURL, L"#" + hhModel->cmetaId())));

#ifdef DUMP_ALL_TRIPLES_FIRST
    {
      ObjRef<iface::rdf_api::TripleSet> ts(dsHH->getAllTriples());
      ObjRef<iface::rdf_api::TripleEnumerator> te(ts->enumerateTriples());
      while (true)
      {
        ObjRef<iface::rdf_api::Triple> t(te->getNextTriple());
        if (t == NULL)
          break;

        displayTriple(t);
      }
    }
#endif

    ObjRef<iface::rdf_api::URIReference> pmid(dsHH->getURIReference(L"http://www.cellml.org/bqs/1.0#Pubmed_id"));
    // Note: Calls like this could fail with an exception if there was no pubmed ID - production code should check.
    ObjRef<iface::rdf_api::Triple> t(hhModelRef->getTripleOutOfByPredicate(pmid));
    ObjRef<iface::rdf_api::Node> n(t->object());
    ObjRef<iface::rdf_api::Literal> lPMID(QueryInterface(n));
    if (lPMID != NULL) // It will be null if for some reason it isn't a literal...
      std::wcout << L"Model pubmed ID: " << lPMID->lexicalForm() << std::endl;
    
    ObjRef<iface::rdf_api::URIReference> bqsReference(dsHH->getURIReference(L"http://www.cellml.org/bqs/1.0#reference"));
    ObjRef<iface::rdf_api::TripleSet> ts(hhModelRef->getTriplesOutOfByPredicate(bqsReference));
    ObjRef<iface::rdf_api::TripleEnumerator> te(ts->enumerateTriples());
    while (true)
    {
      t = te->getNextTriple();
      if (t == NULL) break;
      ObjRef<iface::rdf_api::Resource> r(QueryInterface(t->object()));
      if (r == NULL) continue;
      std::wcout << L"Found a resource description:" << std::endl;
      try
      {
        t = r->getTripleOutOfByPredicate(pmid);
        n = t->object();
        lPMID = QueryInterface(n);
        if (lPMID != NULL)
          std::wcout << L"  Reference pubmed ID: " << lPMID->lexicalForm() << std::endl;
      }
      catch(...) {}
      // Look up the subject...
      ObjRef<iface::rdf_api::URIReference> subject(dsHH->getURIReference(L"http://purl.org/dc/elements/1.1/subject"));
      ts = r->getTriplesOutOfByPredicate(subject);
      ObjRef<iface::rdf_api::TripleEnumerator> te2 = ts->enumerateTriples();
      while (true)
      {
        t = te2->getNextTriple();
        if (t == NULL)
          break;
        n = t->object();
        r = QueryInterface(n);
        if (r == NULL)
          continue;
        std::wcout << "  Subject:" << std::endl;
        ObjRef<iface::rdf_api::URIReference> subjectType(dsHH->getURIReference(L"http://www.cellml.org/bqs/1.0#subject_type"));
        ts = r->getTriplesOutOfByPredicate(subjectType);
        ObjRef<iface::rdf_api::TripleEnumerator> te3 = ts->enumerateTriples();
        t = te3->getNextTriple();
        if (t)
        {
          n = t->object();
          ObjRef<iface::rdf_api::Literal> l(QueryInterface(n));
          std::wcout << "    Subject Type=" << l->lexicalForm() << std::endl;
        }
        ObjRef<iface::rdf_api::URIReference> value(dsHH->getURIReference(L"http://www.w3.org/1999/02/22-rdf-syntax-ns#value"));
        ts = r->getTriplesOutOfByPredicate(value);
        te3 = ts->enumerateTriples();

        t = te3->getNextTriple();
        if (t == NULL) continue;
        n = t->object();
        r = QueryInterface(n);
        if (r == NULL) continue;
        ObjRef<iface::rdf_api::Container> cont(r->correspondingContainer());

        // Add a new entry to the container first...
        ObjRef<iface::rdf_api::PlainLiteral> newPL(dsHH->getPlainLiteral(L"Newly created label", L"en"));
        cont->appendChild(newPL);

        // Delete any labels that match 'giant axon'...
        ObjRef<iface::rdf_api::NodeIterator> ni(cont->iterateChildren());
        while (true)
        {
          ObjRef<iface::rdf_api::Node> n(ni->getNextNode());
          if (n == NULL)
            break;
          ObjRef<iface::rdf_api::Literal> l(QueryInterface(n));
          if (l == NULL)
            continue;
          if (l->lexicalForm() == L"giant axon")
            // The false means don't renumber immediately. This leaves the
            // container with gaps...
            cont->removeChild(l, false);
        }
        cont->renumberContainer(); // Remove the gaps.

        displayContainer(cont, L"    ");
      }      
    }
  }
  catch (iface::cellml_api::CellMLException&)
  {
    std::wcout << L"A CellMLException was raised. In production code, you would normally have more "
               << L"exception handlers to work out exactly where the problem occurred. This program "
               << L"avoids that for simplicity, to make the normal control flow easier to understand. "
               << L"The most likely cause is a network problem retrieving the hardcoded model URL."
               << std::endl;
    return 1;
  }
  catch (iface::rdf_api::RDFProcessingError&)
  {
    std::wcout << L"An RDFProcessingError was raised. In production code, you would normally have more "
               << L"exception handlers to work out exactly where the problem occurred. This program "
               << L"avoids that for simplicity, to make the normal control flow easier to understand."
               << std::endl;
    return 2;
  }
  return 0;
}
コード例 #12
0
	bool importFile(const char * inFolder, const char * inFullPath)
	{
		TypedPinCreator * pPinCreator ;
		if ( !mImporter->beginEmail( inFolder, &pPinCreator ) )
			return false ;

		// Note: currently minimal error handling for invalid files
		FILE * f = fopen( inFullPath, "r" ) ;
		char line[1024]; 

		// Sender name
		if (line != fgets(line, 1024, f)) assert(false);
		line[strlen(line)-1] = '\0' ;    // get rid of \n
		string senderName( line + 6 ) ; // 6 == strlen( "From: ")
		pPinCreator->add( "SenderName", senderName); 

		// Date
		if (line != fgets(line, 1024, f)) assert(false);
		line[strlen(line)-1] = '\0' ; // get rid of \n
		// TODO??? Convert "Sent: Tuesday, November 07, 2006 9:35" into a store Date Time
		pPinCreator->addDateTime( "CreationTime", MVTRand::getDateTime(mSession,false) );

		if (line != fgets(line, 1024, f)) assert(false);
		line[strlen(line)-1] = '\0' ; // get rid of \n
		string subject( line + 9 ) ;
		pPinCreator->add( "Subject", subject ) ;

		string body ;
		while( fgets( line, 1024, f ) )
		{
			body += line ;
		}

		pPinCreator->add( "Body", body ) ;

		fclose(f);

		//
		// Fill out some of the other fields more randomly
		//

		pPinCreator->add( "mime", "Mail/outlook" );
		pPinCreator->add( "Importance", "High" ) ;
		pPinCreator->add( "SenderEmailType", "SMTP" ) ;
		pPinCreator->add( "Sensitivity", "Personal" ) ; //...Private, Confidential...

		pPinCreator->add( "HTMLBody", body ) ;
		pPinCreator->add( "binary", senderName + "\n" + subject + "\n" + body ) ;
		pPinCreator->add( "EntryID", MVTRand::getString2( 50 ) );

		vector<string> addresses ;
		addresses.push_back( mEmailAddresses.getStr() ) ; // Random

		pPinCreator->add( "To", addresses ) ;
		pPinCreator->add( "SenderEmailAddress",  mEmailAddresses.getStr() ) ;

		vector<string> tags ;
		mTags.getPoolSelection( tags, 10, true ) ;  // Could be accumulated list of folders
		pPinCreator->add( "Tag", tags ) ;

		addresses.clear() ;
		mEmailAddresses.getPoolSelection( addresses, 5, true ) ;
		pPinCreator->add( "Cc", addresses ) ;
		
		return mImporter->endEmail( pPinCreator ) ;
	}
コード例 #13
0
ファイル: MQTT.cpp プロジェクト: IanDury/domoticz
void MQTT::on_message(const struct mosquitto_message *message)
{
	std::string topic = message->topic;
	std::string qMessage = std::string((char*)message->payload, (char*)message->payload + message->payloadlen);

	_log.Log(LOG_STATUS, "MQTT: Topic: %s, Message: %s", topic.c_str(), qMessage.c_str());

	if (qMessage.empty())
		return;

	if (topic.find("MyMQTT") != std::string::npos)
	{
		//MySensors message
		ProcessMySensorsMessage(qMessage);
		return;
	}
	else if (topic != TOPIC_IN)
		return;
	Json::Value root;
	Json::Reader jReader;
	std::string szCommand = "udevice";
	std::vector<std::vector<std::string> > result;
	unsigned long long idx = 0;

	bool ret = jReader.parse(qMessage, root);
	if (!ret)
		goto mqttinvaliddata;


	if (!root["command"].empty())
	{
		if (!root["command"].isString())
			goto mqttinvaliddata;
		szCommand = root["command"].asString();
	}

	if ((szCommand == "udevice") || (szCommand == "switchlight") || (szCommand == "getdeviceinfo"))
	{
		if (root["idx"].empty())
			goto mqttinvaliddata;
		if (!root["idx"].isInt64())
			goto mqttinvaliddata;

		idx = (unsigned long long)root["idx"].asInt64();
		//Get the raw device parameters
		result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType FROM DeviceStatus WHERE (ID==%llu)", idx);
		if (result.empty())
		{
			_log.Log(LOG_ERROR, "MQTT: unknown idx received!");
			return;
		}
	}
	else if (szCommand == "switchscene")
	{
		if (root["idx"].empty())
			goto mqttinvaliddata;
		if (!root["idx"].isInt64())
			goto mqttinvaliddata;

		idx = (unsigned long long)root["idx"].asInt64();
		result = m_sql.safe_query("SELECT Name FROM Scenes WHERE (ID==%llu)", idx);
		if (result.empty())
		{
			_log.Log(LOG_ERROR, "MQTT: unknown idx received!");
			return;
		}
	}
	else if (szCommand == "setuservariable")
	{
		if (root["idx"].empty())
			goto mqttinvaliddata;
		if (!root["idx"].isInt64())
			goto mqttinvaliddata;

		idx = (unsigned long long)root["idx"].asInt64();
		result = m_sql.safe_query("SELECT Name FROM UserVariables WHERE (ID==%llu)", idx);
		if (result.empty())
		{
			_log.Log(LOG_ERROR, "MQTT: unknown idx received!");
			return;
		}
	}

	if (szCommand == "udevice")
	{
		int HardwareID = atoi(result[0][0].c_str());
		std::string DeviceID = result[0][1];
		int unit = atoi(result[0][2].c_str());
		int devType = atoi(result[0][3].c_str());
		int subType = atoi(result[0][4].c_str());

		bool bnvalue = !root["nvalue"].empty();
		bool bsvalue = !root["svalue"].empty();
		bool bParseValue = !root["parse"].empty();

		if (!bnvalue && !bsvalue)
			goto mqttinvaliddata;

		if (bnvalue)
		{
			if (!root["nvalue"].isInt())
				goto mqttinvaliddata;
		}
		if (bsvalue)
		{
			if (!root["svalue"].isString())
				goto mqttinvaliddata;
		}

		int nvalue = (bnvalue) ? root["nvalue"].asInt() : 0;
		std::string svalue = (bsvalue) ? root["svalue"].asString() : "";
		bool bParseTrigger = (bParseValue) ? root["parse"].asBool() : true;

		int signallevel = 12;
		int batterylevel = 255;

		if (!m_mainworker.UpdateDevice(HardwareID, DeviceID, unit, devType, subType, nvalue, svalue, signallevel, batterylevel, bParseTrigger))
		{
			_log.Log(LOG_ERROR, "MQTT: Problem updating sensor (check idx, hardware enabled)");
			return;
		}
		return;
	}
	else if (szCommand == "switchlight")
	{
		if (root["switchcmd"].empty())
			goto mqttinvaliddata;
		if (!root["switchcmd"].isString())
			goto mqttinvaliddata;
		std::string switchcmd = root["switchcmd"].asString();
		if ((switchcmd != "On") && (switchcmd != "Off") && (switchcmd != "Toggle") && (switchcmd != "Set Level"))
			goto mqttinvaliddata;
		int level = 0;
		if (!root["level"].empty())
		{
			if (root["level"].isString())
				level = atoi(root["level"].asString().c_str());
			else
				level = root["level"].asInt();
		}
		if (!m_mainworker.SwitchLight(idx, switchcmd, level, -1, false, 0) == true)
		{
			_log.Log(LOG_ERROR, "MQTT: Error sending switch command!");
		}
		return;
	}
	else if (szCommand == "switchscene")
	{
		if (root["switchcmd"].empty())
			goto mqttinvaliddata;
		if (!root["switchcmd"].isString())
			goto mqttinvaliddata;
		std::string switchcmd = root["switchcmd"].asString();
		if ((switchcmd != "On") && (switchcmd != "Off"))
			goto mqttinvaliddata;
		if (!m_mainworker.SwitchScene(idx, switchcmd) == true)
		{
			_log.Log(LOG_ERROR, "MQTT: Error sending scene command!");
		}
		return;
	}
	else if (szCommand == "setuservariable")
	{
		if (root["value"].empty())
			goto mqttinvaliddata;
		if (!root["value"].isString())
			goto mqttinvaliddata;
		std::string varvalue = root["value"].asString();
		m_sql.SetUserVariable(idx, varvalue, true);
		return;
	}
	else if (szCommand == "sendnotification")
	{
		std::string subject(""), body(""), sound("");
		int priority = 0;
		if (!root["subject"].empty())
		{
			if (!root["subject"].isString())
				goto mqttinvaliddata;
			subject = root["subject"].asString();
		}
		if (!root["body"].empty())
		{
			if (!root["body"].isString())
				goto mqttinvaliddata;
			body = root["body"].asString();
		}
		if (!root["priority"].empty())
		{
			if (!root["priority"].isInt())
				goto mqttinvaliddata;
			priority = root["priority"].asInt();
		}
		if (!root["sound"].empty())
		{
			if (!root["sound"].isString())
				goto mqttinvaliddata;
			sound = root["sound"].asString();
		}
		m_notifications.SendMessageEx(NOTIFYALL, subject, body, "", priority, sound, true);
		std::string varvalue = root["value"].asString();
		m_sql.SetUserVariable(idx, varvalue, true);
		return;
	}
	else if (szCommand == "getdeviceinfo")
	{
		int HardwareID = atoi(result[0][0].c_str());
		SendDeviceInfo(HardwareID, idx, "request device", NULL);
		return;
	}
	else
	{
		_log.Log(LOG_ERROR, "MQTT: Unknown command received: %s", szCommand.c_str());
		return;
	}
mqttinvaliddata:
	_log.Log(LOG_ERROR, "MQTT: Invalid data received!");
}
コード例 #14
0
//-------------------------------------------------------------------------------------
bool SendEMailTask::process()
{
	jwsmtp::mailer m(emailaddr_.c_str(), g_kbeSrvConfig.emailServerInfo_.username.c_str(), subject(),
		g_kbeSrvConfig.emailAtivationInfo_.subject.c_str(), g_kbeSrvConfig.emailServerInfo_.smtp_server.c_str(),
		g_kbeSrvConfig.emailServerInfo_.smtp_port, false);

	m.authtype(g_kbeSrvConfig.emailServerInfo_.smtp_auth == 1 ? jwsmtp::mailer::LOGIN : jwsmtp::mailer::PLAIN);  

	std::string mailmessage = message();

	KBEngine::strutil::kbe_replace(mailmessage, "${backlink}", fmt::format("http://{}:{}/{}_{}", 
		cbaddr_,
		cbport_,
		getopkey(),
		code_));

	KBEngine::strutil::kbe_replace(mailmessage, "${username}", emailaddr_);
	KBEngine::strutil::kbe_replace(mailmessage, "${code}", code_);
	mailmessage = KBEngine::strutil::kbe_trim(mailmessage);

	m.setmessageHTML(mailmessage);

	m.username(g_kbeSrvConfig.emailServerInfo_.username.c_str());
	m.password(g_kbeSrvConfig.emailServerInfo_.password.c_str());
	m.send(); // send the mail

	INFO_MSG(fmt::format("SendEMailTask::process: sendmail[{}]: {}\n", getopkey(), m.response()));
	return false;
}