QString PlayListDb::last(QString playListName) {
    QSqlDatabase db = DbConnectionSettings::lastSaved();
    QSqlQuery findQuery(QString("select FileName from %1 order by pid DESC limit 1")
             .arg(tableName(playListName)));
    if (!findQuery.isActive()) return QString();
    findQuery.next();
    return findQuery.value(0).toString();
}
Exemple #2
0
void veroProbeQueryTest() {
	//const wchar_t* sql = L"select * from dual";
	const wchar_t* sql = L"SELECT * INTO \"XTC_A_ABJHBFFB_CFDB_EAJC_IHDD_AADDADBFJCF_Connect\" FROM (SELECT 1 AS COL) AS CHECKTEMP LIMIT 1";

	int result = findQuery(sql, alwaysFailQueries, 7);

	cout << "ProbeQueryTest = " << result << endl;
	cout << "ProbeQueryTest = " << result << endl;
}
QStringList PlayListDb::playList(QString playListName) {
    QSqlDatabase db = DbConnectionSettings::lastSaved();
    QStringList sl;
    QSqlQuery findQuery(QString("select FileName from %1 order by pid").arg(tableName(playListName)));
    if (!findQuery.isActive()) {
        qDebug() << db.lastError().text();
        qDebug() << "Unable to execute: " << findQuery.lastQuery();
    }
    while (findQuery.next()) {
        sl << findQuery.value(0).toString();
    }
    return sl;
}
void PlayListDb::shuffle(QString playListName) {
    QSqlDatabase db = DbConnectionSettings::lastSaved();
    QString tn = tableName(playListName);
    QStringList sl;
    QSqlQuery findQuery(QString("select FileName from %1 order by RAND()").arg(tableName(playListName)));
    if (!findQuery.isActive()) {
        qDebug() << db.lastError().text();
        qDebug() << "Unable to execute: " << findQuery.lastQuery();
    }
    while (findQuery.next()) {
        sl << findQuery.value(0).toString();
    }
    clear(playListName);
    foreach (const QString& fn, sl) {
        addFile(playListName, fn);
    }
void ChartDataCollector::collectData()
{
	SqlQuery * qry=findQuery(m_query);
	if (!qry)
		return;

	Report::ChartInterface::_chartValue cv;
	bool ok;
	switch(m_chartDataSource)
	{
		case FromDatabase:
			if(!qry->record().field(m_valueField).isValid())
				break;

			if(qry->record().field(m_keyField).isValid())
				cv.key=qry->record().field(m_keyField).value().toString();

			if(qry->record().field(m_colorField).isValid())
				cv.color=qry->record().field(m_keyField).value().value<QColor>();
			else
				cv.color=generateNextColor();

			cv.value=qry->record().field(m_valueField).value().toDouble(&ok);
			if (ok)
				addChartValue(cv);
			break;

		case FromScript:
			if (!m_valueScript.length() || !scriptEngine())
				break;
			cv.value=scriptEngine()->evaluate(m_valueScript).toVariant().toDouble(&ok);
			if (!ok)
				break;
			if (m_keyScript.length())
				cv.key=scriptEngine()->evaluate(m_keyScript).toString();

			if (m_colorScript.length())
				cv.color=scriptEngine()->evaluate(m_colorScript).toVariant().value<QColor>();
			else
				cv.color=generateNextColor();
			addChartValue(cv);
			break;
		default:
			break;
	}
}
void ChartDataCollector::setupConnections()
{
	m_chartValues.clear();
	m_otherValue.value=0;
	if (m_chartDataSource!=FromStaticData && m_query.length() && findQuery(m_query))
	{
		findQuery(m_query)->disconnect();
		connect(findQuery(m_query),SIGNAL(afterFirst()),SLOT(collectData()));
		connect(findQuery(m_query),SIGNAL(afterNext()),SLOT(collectData()));
		connect(findQuery(m_query),SIGNAL(afterPrevious()),SLOT(collectData()));
		connect(findQuery(m_query),SIGNAL(afterLast()),SLOT(collectData()));
	}
}
Exemple #7
0
void IRCServer::lineReceivedEvent(char *line, int size) {
	printf("[%d] { %s }\n", size, line);

	// Process this line...!
	UserRef user;

	// Is there a prefix?
	if (line[0] == ':') {
		char nickBuf[512], identBuf[512], hostBuf[512];
		int nickPos = 0, identPos = 0, hostPos = 0;
		int phase = 0;

		++line; // skip colon

		while ((*line != ' ') && (*line != 0)) {
			if (phase == 0) {
				// Nick
				if (*line == '!')
					phase = 1;
				else if (*line == '@')
					phase = 2;
				else {
					if (nickPos < 511)
						nickBuf[nickPos++] = *line;
				}
			} else if (phase == 1) {
				// Ident
				if (*line == '@')
					phase = 2;
				else {
					if (identPos < 511)
						identBuf[identPos++] = *line;
				}
			} else if (phase == 2) {
				if (hostPos < 511)
					hostBuf[hostPos++] = *line;
			}

			++line;
		}

		if (*line == 0) {
			// Invalid line. Can't parse this.
			return;
		}

		++line; // skip the space

		nickBuf[nickPos] = 0;
		identBuf[identPos] = 0;
		hostBuf[hostPos] = 0;

		user.nick = nickBuf;
		user.ident = identBuf;
		user.hostmask = hostBuf;

		user.isValid = true;
		user.isSelf = (strcmp(nickBuf, currentNick) == 0);
	}

	// Get the command
	char cmdBuf[512];
	int cmdPos = 0;

	while ((*line != ' ') && (*line != 0)) {
		if (cmdPos < 511)
			cmdBuf[cmdPos++] = *line;
		++line;
	}
	cmdBuf[cmdPos] = 0;

	if (*line == 0) {
		// Invalid line.
		return;
	}

	++line; // skip the space

	// Skip the : if there is one
	if (*line == ':')
		++line;

	// Get the first param, or "target" in many cases
	char *allParams = line;
	char *paramsAfterFirst = line;

	char targetBuf[512];
	int targetPos = 0;

	while ((*paramsAfterFirst != ' ') && (*paramsAfterFirst != 0)) {
		if (targetPos < 511)
			targetBuf[targetPos++] = *paramsAfterFirst;
		++paramsAfterFirst;
	}

	targetBuf[targetPos] = 0;

	// If we didn't reach the end of the line, skip the space
	if (*paramsAfterFirst == ' ')
		++paramsAfterFirst;

	// And if the params begin with :, skip it
	if (*paramsAfterFirst == ':')
		++paramsAfterFirst;

	// Now figure out what to do with this...!

	if (strcmp(cmdBuf, "PING") == 0) {
		char out[512];
		snprintf(out, 512, "PONG :%s", allParams);
		sendLine(out);
		return;

	} else if (strcmp(cmdBuf, "JOIN") == 0) {
		Channel *c = findChannel(targetBuf, true);
		if (c) {
			c->handleJoin(user);
			return;
		}

	} else if (strcmp(cmdBuf, "PART") == 0) {
		Channel *c = findChannel(targetBuf, false);
		if (c) {
			c->handlePart(user, paramsAfterFirst);
			return;
		}

	} else if (strcmp(cmdBuf, "QUIT") == 0) {
		for (auto &i : channels)
			i.second->handleQuit(user, allParams);

		if (Query *q = findQuery(user.nick.c_str(), false))
			q->handleQuit(allParams);
		return;

	} else if (strcmp(cmdBuf, "KICK") == 0) {
		char *space = strchr(paramsAfterFirst, ' ');
		const char *kickMsg = "";

		if (space) {
			*space = 0;
			kickMsg = space + 1;

			if (*kickMsg == ':')
				++kickMsg;
		}

		Channel *c = findChannel(targetBuf, false);
		if (c) {
			c->handleKick(user, paramsAfterFirst, kickMsg);
			return;
		}

	} else if (strcmp(cmdBuf, "NICK") == 0) {
		if (user.isSelf) {
			strncpy(currentNick, allParams, sizeof(currentNick));
			currentNick[sizeof(currentNick) - 1] = 0;

			ircStringToLowercase(currentNick, currentNickLower, sizeof(currentNickLower));

			char buf[1024];
			snprintf(buf, 1024, "You are now known as %s", currentNick);
			status.pushMessage(buf);

			for (auto &it : queries)
				it.second->showNickChange(user, allParams);
		}

		if (Query *q = findQuery(user.nick.c_str(), false)) {
			if (!user.isSelf)
				q->showNickChange(user, allParams);

			// Should we *rename* the query window, or not?
			Query *check = findQuery(allParams, false);
			if (check) {
				// If we already have one with the destination
				// nick, we shouldn't replace it..
				// ...but we should still show a notification there.
				// Unless check and q are the same, which can happen
				// if a user changes their nick's case. 
				if ((!user.isSelf) && (check != q))
					check->showNickChange(user, allParams);

				// And if the name's case changed, we need to update
				// the title to match!
				if (check->partner != allParams)
					check->renamePartner(allParams);

			} else {
				// We didn't have one, so it's safe to move!
				char lowerName[512];

				// First, remove the old entry..
				ircStringToLowercase(user.nick.c_str(), lowerName, sizeof(lowerName));

				auto iter = queries.find(lowerName);
				queries.erase(iter);

				// ...and then add a new one
				ircStringToLowercase(allParams, lowerName, sizeof(lowerName));
				queries[lowerName] = q;

				q->renamePartner(allParams);
			}
		}

		for (auto &i : channels)
			i.second->handleNick(user, allParams);

		return;

	} else if (strcmp(cmdBuf, "MODE") == 0) {
		Channel *c = findChannel(targetBuf, false);
		if (c) {
			c->handleMode(user, paramsAfterFirst);
			return;
		}

	} else if (strcmp(cmdBuf, "TOPIC") == 0) {
		Channel *c = findChannel(targetBuf, false);
		if (c) {
			c->handleTopic(user, paramsAfterFirst);
			return;
		}

	} else if (strcmp(cmdBuf, "PRIVMSG") == 0) {

		int endPos = strlen(paramsAfterFirst) - 1;
		bool requireQueryWindow = true;
		const char *ctcpType = NULL, *ctcpParams = NULL;

		if ((endPos > 0) &&
			(paramsAfterFirst[0] == 1) &&
			(paramsAfterFirst[endPos] == 1))
		{
			// Try to parse a CTCP
			// Cut off the 01 char at the end
			paramsAfterFirst[endPos] = 0;

			// Split the string into type + params
			char *space = strchr(paramsAfterFirst, ' ');

			ctcpType = &paramsAfterFirst[1];

			if (space) {
				*space = 0;
				ctcpParams = space + 1;
			} else {
				ctcpParams = "";
			}

			if (strcmp(ctcpType, "ACTION") != 0)
				requireQueryWindow = false;

			// This needs to be extracted into a separate
			// method at some point
			if (strcmp(ctcpType, "VERSION") == 0) {
				char reply[1000];
				snprintf(reply, sizeof(reply),
					"NOTICE %s :\x01VERSION " VULPIRC_VERSION_STRING "\x01",
					user.nick.c_str());
				sendLine(reply);

			} else if (strcmp(ctcpType, "PING") == 0) {
				char reply[1000];
				snprintf(reply, sizeof(reply),
					"NOTICE %s :\x01PING %s\x01",
					user.nick.c_str(),
					ctcpParams);
				sendLine(reply);

			} else if (strcmp(ctcpType, "TIME") == 0) {
				char reply[1000], formatTime[200];
				time_t now = time(NULL);
				tm *nowtm = localtime(&now);

				strftime(formatTime, sizeof(formatTime),
					"%c", nowtm);

				snprintf(reply, sizeof(reply),
					"NOTICE %s :\x01TIME :%s\x01",
					user.nick.c_str(),
					formatTime);
				sendLine(reply);
			}
		}



		char targetBufLower[512];
		ircStringToLowercase(targetBuf, targetBufLower, 512);

		if (strcmp(targetBufLower, currentNickLower) == 0) {
			Query *q = findQuery(user.nick.c_str(), requireQueryWindow);
			if (q) {
				if (ctcpType)
					q->handleCtcp(user, ctcpType, ctcpParams);
				else
					q->handlePrivmsg(user, paramsAfterFirst);
				return;
			} else if (ctcpType) {
				// This CTCP didn't require a query window to be
				// open, and we don't already have one, so
				// dump a notification into the status window.
				char buf[1000];
				snprintf(buf, sizeof(buf),
					"CTCP from %s : %s %s",
					user.nick.c_str(),
					ctcpType,
					ctcpParams);
				status.pushMessage(buf);
				return;
			}
		} else {
			if (isValidChannelName(targetBuf)) {
				Channel *c = findChannel(targetBuf, true);
				if (c) {
					if (ctcpType)
						c->handleCtcp(user, ctcpType, ctcpParams);
					else
						c->handlePrivmsg(user, paramsAfterFirst);
					return;
				}
			} else {
				Query *q = findQuery(targetBuf, true);
				if (q) {
					if (ctcpType)
						q->handleCtcp(user, ctcpType, ctcpParams);
					else
						q->handlePrivmsg(user, paramsAfterFirst);
					return;
				}
			}
		}

	} else if (strcmp(cmdBuf, "001") == 0) {
		status.pushMessage("[debug: currentNick change detected]");

		strncpy(currentNick, targetBuf, sizeof(currentNick));
		currentNick[sizeof(currentNick) - 1] = 0;

		ircStringToLowercase(currentNick, currentNickLower, sizeof(currentNickLower));
	}

	int n = atoi(cmdBuf);
	if ((n > 0) && (n <= 999) && (strlen(cmdBuf) == 3)) {
		if (dispatchNumeric(n, paramsAfterFirst))
			return;
	}

	char tmpstr[2048];
	if (user.isValid)
		snprintf(tmpstr, sizeof(tmpstr),
			"[[Unhandled \"%s\" from %s!%s@%s]]",
			cmdBuf, user.nick.c_str(), user.ident.c_str(), user.hostmask.c_str());
	else
		snprintf(tmpstr, sizeof(tmpstr),
			"[[Unhandled \"%s\"]]",
			cmdBuf);

	status.pushMessage(tmpstr);
	status.pushMessage(line);
}
Exemple #8
0
Query *IRCServer::createQuery(const char *name) {
	return findQuery(name, true);
}
  bool OrthancFindRequestHandler::Handle(DicomFindAnswers& answers,
                                         const DicomMap& input,
                                         const std::string& callingAETitle)
  {
    /**
     * Ensure that the calling modality is known to Orthanc.
     **/

    RemoteModalityParameters modality;

    if (!Configuration::LookupDicomModalityUsingAETitle(modality, callingAETitle))
    {
      throw OrthancException("Unknown modality");
    }

    // ModalityManufacturer manufacturer = modality.GetManufacturer();

    bool caseSensitivePN = Configuration::GetGlobalBoolParameter("CaseSensitivePN", false);


    /**
     * Retrieve the query level.
     **/

    const DicomValue* levelTmp = input.TestAndGetValue(DICOM_TAG_QUERY_RETRIEVE_LEVEL);
    if (levelTmp == NULL) 
    {
      throw OrthancException(ErrorCode_BadRequest);
    }

    ResourceType level = StringToResourceType(levelTmp->AsString().c_str());

    if (level != ResourceType_Patient &&
        level != ResourceType_Study &&
        level != ResourceType_Series &&
        level != ResourceType_Instance)
    {
      throw OrthancException(ErrorCode_NotImplemented);
    }


    DicomArray query(input);
    LOG(INFO) << "DICOM C-Find request at level: " << EnumerationToString(level);

    for (size_t i = 0; i < query.GetSize(); i++)
    {
      if (!query.GetElement(i).GetValue().IsNull())
      {
        LOG(INFO) << "  " << query.GetElement(i).GetTag()
                  << "  " << FromDcmtkBridge::GetName(query.GetElement(i).GetTag())
                  << " = " << query.GetElement(i).GetValue().AsString();
      }
    }


    /**
     * Build up the query object.
     **/

    CFindQuery findQuery(answers, context_.GetIndex(), query);
    findQuery.SetLevel(level);
        
    for (size_t i = 0; i < query.GetSize(); i++)
    {
      const DicomTag tag = query.GetElement(i).GetTag();

      if (query.GetElement(i).GetValue().IsNull() ||
          tag == DICOM_TAG_QUERY_RETRIEVE_LEVEL ||
          tag == DICOM_TAG_SPECIFIC_CHARACTER_SET)
      {
        continue;
      }

      std::string value = query.GetElement(i).GetValue().AsString();
      if (value.size() == 0)
      {
        // An empty string corresponds to a "*" wildcard constraint, so we ignore it
        continue;
      }

      if (tag == DICOM_TAG_MODALITIES_IN_STUDY)
      {
        findQuery.SetModalitiesInStudy(value);
      }
      else
      {
        findQuery.SetConstraint(tag, value, caseSensitivePN);
      }
    }


    /**
     * Run the query.
     **/

    ResourceFinder finder(context_);

    switch (level)
    {
      case ResourceType_Patient:
      case ResourceType_Study:
      case ResourceType_Series:
        finder.SetMaxResults(maxResults_);
        break;

      case ResourceType_Instance:
        finder.SetMaxResults(maxInstances_);
        break;

      default:
        throw OrthancException(ErrorCode_InternalError);
    }

    std::list<std::string> tmp;
    bool finished = finder.Apply(tmp, findQuery);

    LOG(INFO) << "Number of matching resources: " << tmp.size();

    return finished;
  }
Exemple #10
0
static int
dnsReplyHandler(int abort, FdEventHandlerPtr event)
{
    int fd = event->fd;
    char buf[2048];
    int len, rc;
    ObjectPtr object;
    unsigned ttl = 0;
    AtomPtr name, value, message = NULL;
    int id;
    int af;
    DnsQueryPtr query;
    AtomPtr cname = NULL;

    if(abort) {
        dnsSocketHandler = NULL;
        rc = establishDnsSocket();
        if(rc < 0) {
            do_log(L_ERROR, "Couldn't reestablish DNS socket.\n");
            /* At this point, we should abort all in-flight
               DNS requests.  Oh, well, they'll timeout anyway. */
        }
        return 1;
    }

    len = recv(fd, buf, 2048, 0);
    if(len <= 0) {
        if(errno == EINTR || errno == EAGAIN) return 0;
        /* This is where we get ECONNREFUSED for an ICMP port unreachable */
        do_log_error(L_ERROR, errno, "DNS: recv failed");
        dnsGethostbynameFallback(-1, message);
        return 0;
    }

    /* This could be a late reply to a query that timed out and was
       resent, a reply to a query that timed out, or a reply to an
       AAAA query when we already got a CNAME reply to the associated
       A.  We filter such replies straight away, without trying to
       parse them. */
    rc = dnsReplyId(buf, 0, len, &id);
    if(rc < 0) {
        do_log(L_WARN, "Short DNS reply.\n");
        return 0;
    }
    if(!findQuery(id, NULL)) {
        return 0;
    }

    rc = dnsDecodeReply(buf, 0, len, &id, &name, &value, &af, &ttl);
    if(rc < 0) {
        assert(value == NULL);
        /* We only want to fallback on gethostbyname if we received a
           reply that we could not understand.  What about truncated
           replies? */
        if(rc < 0) {
            do_log_error(L_WARN, -rc, "DNS");
            if(dnsUseGethostbyname >= 2 ||
               (dnsUseGethostbyname && 
                (rc != -EDNS_HOST_NOT_FOUND && rc != -EDNS_NO_RECOVERY &&
                 rc != -EDNS_FORMAT))) {
                dnsGethostbynameFallback(id, message);
                return 0;
            } else {
                message = internAtom(pstrerror(-rc));
            }
        } else {
            assert(name != NULL && id >= 0 && af >= 0);
        }
    }

    query = findQuery(id, name);
    if(query == NULL) {
        /* Duplicate id ? */
        releaseAtom(value);
        releaseAtom(name);
        return 0;
    }

    /* We're going to use the information in this reply.  If it was an
       error, construct an empty atom to distinguish it from information
       we're still waiting for. */
    if(value == NULL)
        value = internAtom("");

 again:
    if(af == 4) {
        if(query->inet4 == NULL) {
            query->inet4 = value;
            query->ttl4 = current_time.tv_sec + ttl;
        } else
            releaseAtom(value);
    } else if(af == 6) {
        if(query->inet6 == NULL) {
            query->inet6 = value;
            query->ttl6 = current_time.tv_sec + ttl;
        } else
            releaseAtom(value);
    } else if(af == 0) {
        /* Ignore errors in this case. */
        if(query->inet4 && query->inet4->length == 0) {
            releaseAtom(query->inet4);
            query->inet4 = NULL;
        }
        if(query->inet6 && query->inet6->length == 0) {
            releaseAtom(query->inet6);
            query->inet6 = NULL;
        }
        if(query->inet4 || query->inet6) {
            do_log(L_WARN, "Host %s has both %s and CNAME -- "
                   "ignoring CNAME.\n", scrub(query->name->string),
                   query->inet4 ? "A" : "AAAA");
            releaseAtom(value);
            value = internAtom("");
            af = query->inet4 ? 4 : 6;
            goto again;
        } else {
            cname = value;
        }
    }

    if(rc >= 0 && !cname &&
       ((dnsQueryIPv6 < 3 && query->inet4 == NULL) ||
        (dnsQueryIPv6 > 0 && query->inet6 == NULL)))
        return 0;

    /* This query is complete */

    cancelTimeEvent(query->timeout_handler);
    object = query->object;

    if(object->flags & OBJECT_INITIAL) {
        assert(!object->headers);
        if(cname) {
            assert(query->inet4 == NULL && query->inet6 == NULL);
            object->headers = cname;
            object->expires = current_time.tv_sec + ttl;
        } else if((!query->inet4 || query->inet4->length == 0) &&
                  (!query->inet6 || query->inet6->length == 0)) {
            releaseAtom(query->inet4);
            releaseAtom(query->inet6);
            object->expires = current_time.tv_sec + dnsNegativeTtl;
            abortObject(object, 500, retainAtom(message));
        } else if(!query->inet4 || query->inet4->length == 0) {
            object->headers = query->inet6;
            object->expires = query->ttl6;
            releaseAtom(query->inet4);
        } else if(!query->inet6 || query->inet6->length == 0) {
            object->headers = query->inet4;
            object->expires = query->ttl4;
            releaseAtom(query->inet6);
        } else {
            /* need to merge results */
            char buf[1024];
            if(query->inet4->length + query->inet6->length > 1024) {
                releaseAtom(query->inet4);
                releaseAtom(query->inet6);
                abortObject(object, 500, internAtom("DNS reply too long"));
            } else {
                if(dnsQueryIPv6 <= 1) {
                    memcpy(buf, query->inet4->string, query->inet4->length);
                    memcpy(buf + query->inet4->length,
                           query->inet6->string + 1, query->inet6->length - 1);
                } else {
                    memcpy(buf, query->inet6->string, query->inet6->length);
                    memcpy(buf + query->inet6->length,
                           query->inet4->string + 1, query->inet4->length - 1);
                }
                object->headers =
                    internAtomN(buf, 
                                query->inet4->length + 
                                query->inet6->length - 1);
                if(object->headers == NULL)
                    abortObject(object, 500, 
                                internAtom("Couldn't allocate DNS atom"));
            }
            object->expires = MIN(query->ttl4, query->ttl6);
        }
        object->age = current_time.tv_sec;
        object->flags &= ~(OBJECT_INITIAL | OBJECT_INPROGRESS);
    } else {
        do_log(L_WARN, "DNS object ex nihilo for %s.\n",
               scrub(query->name->string));
    }
    
    removeQuery(query);
    free(query);

    releaseAtom(name);
    releaseAtom(message);
    releaseNotifyObject(object);
    return 0;
}
Exemple #11
0
int findInAlwaysFailQuery ( const wchar_t* sql ) {
    return findQuery ( sql, alwaysFailQueries, sizeof ( alwaysFailQueries ) / sizeof ( wchar_t* ) );
}