コード例 #1
0
ファイル: serverdatabase.cpp プロジェクト: darthvid/sion
/**
 * Gets a file attribute value from the db
 *
 * @param filterId is the filter id
 * @param filepath is the full pathname of the new file
 * @param attrName is the name of the file attribute
 */
QString ServerDatabase::getFileAttribute(QString filterId, QString filepath, QString attrName) {
    QString result;

    m_dbSem.acquire();

    QSqlQuery query(m_db);

    sanitizeString(filepath);
    sanitizeString(attrName);

#ifdef _VERBOSE_DATABASE
        qDebug() << "retrieving file attribute " << filterId << "/" << filepath << "/" << attrName;
#endif

    // select tuple fiterId/filepath/attrName if existing
    if (!query.exec("SELECT attributes.attribute_value FROM files, attributes WHERE files.path='" + filepath + "' AND files.filter_id=" + filterId + " AND files.file_id=attributes.file_id AND attribute_name='" + attrName + "'")) {
        qDebug() << QObject::tr("Failed to select from attributes table in DB ") + DB_NAME + QObject::tr(" on host ") + DB_HOST + QObject::tr(" with usr/pwd ") + DB_USR + "/" + DB_PWD;
        qDebug() << QObject::tr("ERROR: ") + query.lastError().text();
    } else if (query.next()) {
        result = query.value(0).toString();
        unsanitizeString(result);

#ifdef _VERBOSE_DATABASE
        qDebug() << "retrieved file attribute " << filterId << "/" << filepath << "/" << attrName << ": " << result;
#endif
    }

    m_dbSem.release();

    return result;
}
コード例 #2
0
ファイル: serverdatabase.cpp プロジェクト: darthvid/sion
/**
 * Adds a new (unique) file reference to the db
 *
 * @param filterId is the filter id
 * @param filepath is the full pathname of the new file
 * @return the file id of the new file
 */
QString ServerDatabase::addFile(QString filterId, QString filepath) {
    m_dbSem.acquire();

    QString fileId;
    QSqlQuery query(m_db);

    sanitizeString(filepath);

#ifdef _VERBOSE_DATABASE
    qDebug() << "adding file " << filterId << "/" << filepath;
#endif

    // check if file exists
    query.exec("SELECT file_id FROM files WHERE path='" + filepath + "' AND filter_id=" + filterId);
    if (query.next())
        fileId = query.value(0).toString();
    else {
        if (!query.exec("INSERT INTO files(path, filter_id) VALUES('" + filepath + "', " + filterId + ")")) {
            qDebug() << QObject::tr("Failed to insert (") << filterId << ", " << filepath << QObject::tr(") into the files table.");
            qDebug() << QObject::tr("ERROR: ") << query.lastError().text();
        } else {
            query.exec("SELECT file_id FROM files WHERE path='" + filepath + "' AND filter_id=" + filterId);
            if (query.next())
                fileId = query.value(0).toString();
        }
    }

    m_dbSem.release();

    return fileId;
}
コード例 #3
0
ファイル: serverdatabase.cpp プロジェクト: darthvid/sion
/**
 * Gets the file attribute names/values. Returns a QStringList of attribute names.
 *
 * @param filterId is the filter id
 * @param filepath is the full pathname of the file
 */
QStringList ServerDatabase::getFileAttributes(QString filterId, QString filepath) {
    m_dbSem.acquire();

    QStringList result;

    QSqlQuery query(m_db);

    sanitizeString(filepath);

#ifdef _VERBOSE_DATABASE
    qDebug() << "getting file attributes for " << filterId << "/" << filepath;
#endif

    // get all tuples vdir/File
    query.exec("SELECT attributes.attribute_name FROM files, attributes WHERE files.path='" + filepath + "' AND files.file_id=attributes.file_id AND files.filter_id=" + filterId);
    while (query.next()) {
        QString name = query.value(0).toString();
        unsanitizeString(name);

        result += name;  // "attribute_name" column value

#ifdef _VERBOSE_DATABASE
        qDebug() << "retrieved file attribute name for " << filterId << "/" << filepath << ": " << name;
#endif
    }

    m_dbSem.release();

    return result;
}
コード例 #4
0
ファイル: serverdatabase.cpp プロジェクト: darthvid/sion
/**
  * Retrieves a filter id from its virtual directory path from the filters database.
  *
  * @param virtualDirectoryPath is the filter virtual path
  * @return the associated filter id or an empty string if not found
  */
QString ServerDatabase::getFilterId(QString virtualDirectoryPath) {
    QString filterId;

    m_dbSem.acquire();

    QSqlQuery query(m_db);

    sanitizeString(virtualDirectoryPath);

#ifdef _VERBOSE_DATABASE
    qDebug() << "retrieving filter id for " << virtualDirectoryPath;
#endif

    // retrieve filter_id for the given virtualDirectoryPath
    if (!query.exec("SELECT filter_id FROM filters WHERE virtual_directory='" + virtualDirectoryPath + "'")) {
        qDebug() << QObject::tr("Failed to select from filters table in DB ") + DB_NAME + QObject::tr(" on host ") + DB_HOST + QObject::tr(" with usr/pwd ") + DB_USR + "/" + DB_PWD;
        qDebug() << QObject::tr("ERROR: ") + query.lastError().text();
    } else {
        query.next();
        filterId = query.value(0).toString();

#ifdef _VERBOSE_DATABASE
        qDebug() << "retrieved filter id for " << virtualDirectoryPath << ": " << filterId;
#endif
    }

    m_dbSem.release();

    return filterId;
}
コード例 #5
0
ファイル: serverdatabase.cpp プロジェクト: darthvid/sion
/**
 * Search for a file reference in the db
 *
 * @param filterId is the filter id
 * @param filepath is the full pathname of the new file
 * @return file reference was found
 */
bool ServerDatabase::hasFile(QString filterId, QString filepath) {
    bool result = FALSE;

    m_dbSem.acquire();

    QSqlQuery query(m_db);

    sanitizeString(filepath);

#ifdef _VERBOSE_DATABASE
    qDebug() << "Checking if " << filterId << "/" << filepath << " have file(s) in db";
#endif

    // check if file exists
    if (!query.exec("SELECT filter_id FROM files WHERE path='" + filepath + "' AND filter_id=" + filterId))
        goto hasFileEnd;

    // if the result set is not empty, we can move to the next selected tuple...
    if (query.next())
            result = TRUE;

hasFileEnd:
    m_dbSem.release();

#ifdef _VERBOSE_DATABASE
    qDebug() << "Checking if " << filterId << "/" << filepath << " have file(s) in db reports: " << result;
#endif

    return result;
}
コード例 #6
0
ファイル: serverdatabase.cpp プロジェクト: darthvid/sion
/**
 * Removes a file reference from the db
 *
 * @param filterId is the filter id
 * @param filepath is the full pathname of the new file
 */
void ServerDatabase::removeFile(QString filterId, QString filepath) {
    m_dbSem.acquire();

    QSqlQuery query(m_db);

    sanitizeString(filepath);

#ifdef _VERBOSE_DATABASE
    qDebug() << "removing file " << filterId << "/" << filepath;
#endif

    // retrieve file_id for the given file, filterId
    if (!query.exec("SELECT file_id FROM files WHERE path='" + filepath + "' AND filter_id=" + filterId)) {
        qDebug() << QObject::tr("Failed to delete from attributes table in DB ") + DB_NAME + QObject::tr(" on host ") + DB_HOST + QObject::tr(" with usr/pwd ") + DB_USR + "/" + DB_PWD;
        qDebug() << QObject::tr("ERROR: ") + query.lastError().text();
    } else if (query.next()) {
        QString fileId = query.value(0).toString();

        if (!query.exec("DELETE FROM files WHERE file_id=" + fileId)) {
            qDebug() << QObject::tr("Failed to delete from files table in DB ") + DB_NAME + QObject::tr(" on host ") + DB_HOST + QObject::tr(" with usr/pwd ") + DB_USR + "/" + DB_PWD;
            qDebug() << QObject::tr("ERROR: ") + query.lastError().text();
        }

        if (!query.exec("DELETE FROM attributes WHERE file_id=" + fileId)) {
            qDebug() << QObject::tr("Failed to delete from attributes table in DB ") + DB_NAME + QObject::tr(" on host ") + DB_HOST + QObject::tr(" with usr/pwd ") + DB_USR + "/" + DB_PWD;
            qDebug() << QObject::tr("ERROR: ") + query.lastError().text();
        }
    }

    m_dbSem.release();
}
コード例 #7
0
ファイル: jsonserializer.cpp プロジェクト: ProgVal/JSONBus
void JSONSerializer::serialize(const QVariant &variant) {
	if (!variant.isValid()) { // Case of JSON null/undefined
		// TODO:find a way to differenciate null/undefined
		m_stream << JSON_NULL;
	} else if (variant.type() == QVariant::Bool) { // Case of JSON boolean
		m_stream << (variant.toBool() ? JSON_TRUE: JSON_FALSE);
	} else if (variant.type() == QVariant::Map) { // Case of JSON object
		m_stream << JSON_OBJECT_BEGIN;
		const QVariantMap elements = variant.toMap();
		auto it = elements.begin();
		if (it != elements.end()) {
			m_stream << sanitizeString(it.key()) << JSON_MEMBER_SEP;
			serialize(it.value());
			it++;
		}
		while (it != elements.end()) {
			m_stream << JSON_ELEMENT_SEP << sanitizeString(it.key()) << JSON_MEMBER_SEP;
			serialize(it.value());
			it++;
		}
		m_stream << JSON_OBJECT_END;
	} else if (variant.type() == QVariant::List) { // Case of JSON array
		m_stream << JSON_ARRAY_BEGIN;
		const QVariantList elements = variant.toList();
		auto it = elements.begin();
		if (it != elements.end()) {
			serialize(*it);
			it++;
		}
		while (it != elements.end()) {
			m_stream << JSON_MEMBER_SEP;
			serialize(*it);
			it++;
		}
		m_stream << JSON_ARRAY_END;
	} else if ((variant.type() == QVariant::String) 
		|| (variant.type() == QVariant::ByteArray)) { // Case of JSON string
		m_stream << sanitizeString(variant.toString());
	} else if ((variant.type() == QVariant::Double) || variant.canConvert<double>()) {
		m_stream << QString::number(variant.toDouble()).replace("inf", "infinity");
	} else if ((variant.type() == QVariant::String) || variant.canConvert<QString>()) {
		m_stream << variant.toString();
	} else {
		throw JSONSerializerException("Fatal: QVariant type not managed.");
	}
}
コード例 #8
0
static void android_os_Trace_nativeAsyncTraceEnd(JNIEnv* env, jclass clazz,
        jlong tag, jstring nameStr, jint cookie) {
    const size_t MAX_SECTION_NAME_LEN = 127;
    ScopedStringChars jchars(env, nameStr);
    String8 utf8Chars(reinterpret_cast<const char16_t*>(jchars.get()), jchars.size());
    sanitizeString(utf8Chars);
    atrace_async_end(tag, utf8Chars.string(), cookie);
}
コード例 #9
0
static void android_os_Trace_nativeTraceBegin(JNIEnv* env, jclass clazz,
        jlong tag, jstring nameStr) {
    ScopedStringChars jchars(env, nameStr);
    String8 utf8Chars(reinterpret_cast<const char16_t*>(jchars.get()), jchars.size());
    sanitizeString(utf8Chars);

    ALOGV("%s: %lld %s", __FUNCTION__, tag, utf8Chars.string());
    atrace_begin(tag, utf8Chars.string());
}
コード例 #10
0
static void android_os_Trace_nativeAsyncTraceEnd(JNIEnv* env, jclass clazz,
        jlong tag, jstring nameStr, jint cookie) {
    ScopedStringChars jchars(env, nameStr);
    String8 utf8Chars(reinterpret_cast<const char16_t*>(jchars.get()), jchars.size());
    sanitizeString(utf8Chars);

    ALOGV("%s: %lld %s %d", __FUNCTION__, tag, utf8Chars.string(), cookie);
    atrace_async_end(tag, utf8Chars.string(), cookie);
}
コード例 #11
0
static void android_os_Trace_nativeAsyncTraceBegin(JNIEnv* env, jclass clazz,
        jlong tag, jstring nameStr, jint cookie) {
    const size_t MAX_SECTION_NAME_LEN = 127;
    ScopedStringChars jchars(env, nameStr);
    String8 utf8Chars(reinterpret_cast<const char16_t*>(jchars.get()), jchars.size());
    sanitizeString(utf8Chars);

    ALOGV("%s: %lld %s %d", __FUNCTION__, (long long int)tag, utf8Chars.string(), cookie);
    //atrace_async_begin(tag, utf8Chars.string(), cookie);
}
void CanOpenController::addNode(const uint8_t node_id, const std::string& group_name)
{
  std::string sanitized_identifier = sanitizeString(group_name);
  std::map<std::string, DS301Group::Ptr>::iterator group_it;
  group_it = m_groups.find(sanitized_identifier);


  if (m_nodes.find(node_id) == m_nodes.end())
  {
    if (group_it != m_groups.end())
    {
      DS301Node::Ptr new_node;

      // TODO: Maybe this can be done prettier with templates, however for now this works
      DS402Group::Ptr ds402_ptr;
      if (ds402_ptr = boost::dynamic_pointer_cast<DS402Group>(group_it->second))
      {
        new_node = ds402_ptr->addNode<NodeT>(node_id, m_can_device, m_heartbeat_monitor);
      }
      else
      {
        new_node = group_it->second->addNode<NodeT>(node_id, m_can_device, m_heartbeat_monitor);
      }

      #ifdef _IC_BUILDER_ICL_COMM_WEBSOCKET_
        new_node->registerWSBroadcaster(m_ws_broadcaster);
      #endif // _IC_BUILDER_ICL_COMM_WEBSOCKET_

      m_nodes.insert (std::pair<uint8_t, DS301Node::Ptr>(node_id, new_node));
    }
    else
    {
      LOGGING_ERROR_C(CanOpen, CanOpenController, "No group with the given index " << sanitized_identifier
        << " exists. New node not added!" << endl);
    }
  }
  else
  {
    LOGGING_ERROR_C(CanOpen, CanOpenController, "Node with CANOPEN ID " << node_id
      << " already exists. Not adding new node."  << endl);
  }
}
void CanOpenController::addGroup(const std::string& identifier)
{
  std::string sanitized_identifier = sanitizeString(identifier);
  if (m_groups.find(sanitized_identifier) == m_groups.end())
  {
    DS301Group::Ptr group(new GroupT(sanitized_identifier));

    #ifdef _IC_BUILDER_ICL_COMM_WEBSOCKET_
    group->registerWSBroadcaster(m_ws_broadcaster);
    #endif // _IC_BUILDER_ICL_COMM_WEBSOCKET_

    m_groups[sanitized_identifier] = group;

  }
  else
  {
    LOGGING_ERROR_C(CanOpen, CanOpenController, "Group with the given identifier " << sanitized_identifier
      << " already exists. Not adding new group." << endl);
  }
}
コード例 #14
0
ファイル: json.cpp プロジェクト: shinsterneck/hotshots
QByteArray serializeMap(const T &map, bool &success)
{
    QByteArray str = "{ ";
    QList<QByteArray> pairs;
    for (typename T::const_iterator it = map.begin(), itend = map.end(); it != itend; ++it)
    {
        QByteArray serializedValue = serialize( it.value() );

        if( serializedValue.isNull() )
        {
            success = false;
            break;
        }

        pairs << sanitizeString( it.key() ).toUtf8() + " : " + serializedValue;
    }

    str += join(pairs, ", ");
    str += " }";
    return str;
}
boost::shared_ptr<GroupT> CanOpenController::getGroup (const std::string& index)
{
    std::string sanitized_index = sanitizeString(index);
    boost::shared_ptr<GroupT> group;
    if (m_groups.find(sanitized_index) != m_groups.end())
    {
      group = boost::dynamic_pointer_cast<GroupT>(m_groups[sanitized_index]);
      if (!group)
      {
        LOGGING_ERROR_C(CanOpen, CanOpenController, "Cannot cast group to requested type. Returning null pointer." << endl);
      }
    }
    else
    {
      std::stringstream ss;
      ss << "No group with the given index " << sanitized_index
        << " exists. Returning null pointer.";
      throw NotFoundException(ss.str());
    }
    return group;
  }
コード例 #16
0
ファイル: serverdatabase.cpp プロジェクト: darthvid/sion
/**
  * Adds a filter virtual directory path to the filters database
  * if not already there.
  *
  * @param virtualDirectoryPath is the filter path
  */
void ServerDatabase::addFilter(QString virtualDirectoryPath) {
    m_dbSem.acquire();

    QSqlQuery query(m_db);

    sanitizeString(virtualDirectoryPath);

#ifdef _VERBOSE_DATABASE
    qDebug() << "adding filter " << virtualDirectoryPath;
#endif

    // check if filter exists
    query.exec("SELECT * FROM filters WHERE virtual_directory='" + virtualDirectoryPath + "'");
    if (!query.next()) {
        if (!query.exec("INSERT INTO filters(virtual_directory) VALUES('" + virtualDirectoryPath + "')")) {
            qDebug() << QObject::tr("Failed to insert (") << virtualDirectoryPath << QObject::tr(") into the filters table.");
            qDebug() << QObject::tr("ERROR: ") << query.lastError().text();
        }
    }

    m_dbSem.release();
}
コード例 #17
0
ファイル: oc3_json.cpp プロジェクト: bodgergely/opencaesar3
std::string Json::serialize(const Variant &data, bool &success, const std::string& tab)
{
  std::string str;
  success = true;

  if( !data.isValid() ) // invalid or null?
  {
    str = "null";
  }

  else if( (data.type() == Variant::List) || (data.type() == Variant::NStringArray) ) // variant is a list?
  {
    StringArray values;
    const VariantList rlist = data.toList();
    for( VariantList::const_iterator it = rlist.begin(); it != rlist.end(); it++)
    {
      std::string serializedValue = serialize( *it, "" );
      if( serializedValue.empty() )
      {
          success = false;
          break;
      }

      values.push_back( serializedValue );
    }

    str = "[ " + join( values, ", " ) + " ]";
  }
// 	else if(data.type() == Variant::Hash) // variant is a hash?
// 	{
// 		const VariantHash vhash = data.toHash();
// 		QHashIterator<std::string, Variant> it( vhash );
// 		str = "{ ";
// 		QList<QByteArray> pairs;
// 
// 		while(it.hasNext())
// 		{
// 			it.next();
//               QByteArray serializedValue = serialize(it.value(), "");
// 
// 			if(serializedValue.isNull())
// 			{
// 				success = false;
// 				break;
// 			}
// 
//               pairs << tab.toAscii() + sanitizeString(it.key()).toUtf8() + " : " + serializedValue;
// 		}
// 
// 		str += join(pairs, ", ");
// 		str += " }";
// 	}
    else if(data.type() == Variant::Map) // variant is a map?
    {
      VariantMap vmap = data.toMap();
      
      str = "{ \n";
      StringArray pairs;
      for( VariantMap::iterator it = vmap.begin(); it != vmap.end(); it++ )
      {        
        std::string serializedValue = serialize( it->second, tab + "  ");
        if( serializedValue.empty())
        {
                //success = false;
          pairs.push_back( tab + sanitizeString( it->first ) + std::string( " : \"nonSerializableValue\"" ) );
          continue;
        }
        pairs.push_back( tab + sanitizeString( it->first ) + " : " + serializedValue );
      }
      str += join(pairs, ",\n");
      std::string rtab( tab );
      rtab.resize( std::max<int>( 0, tab.size() - 2 ) );
      str += std::string( "\n" ) + rtab + "}";
    }
    else if((data.type() == Variant::String) || (data.type() == Variant::NByteArray)) // a string or a byte array?
    {
            str = sanitizeString( data.toString() );
    }
    else if(data.type() == Variant::Double || data.type() == Variant::Float) // double?
    {
      str = StringHelper::format( 0xff, "\"%f\"", data.toDouble() );
      if( str.find(".") == std::string::npos && str.find("e") == std::string::npos )
      {
         str += ".0";
      }
    }
    else if( data.type() == Variant::NTilePos)
    {
      TilePos pos = data.toTilePos();
      str = StringHelper::format( 0xff, "[ %d, %d ]", pos.getI(), pos.getJ() );
    }
    else if( data.type() == Variant::NSize)
    {
      Size size = data.toSize();
      str = StringHelper::format( 0xff, "[ %d, %d ]", size.getWidth(), size.getHeight() );
    }
    else if( data.type() == Variant::NPoint)
    {
      Point pos = data.toPoint();
      str = StringHelper::format( 0xff, "[ %d, %d ]", pos.getX(), pos.getY() );
    }
    else if( data.type() == Variant::NPointF)
    {
      PointF pos = data.toPointF();
      str = StringHelper::format( 0xff, "[ \"%f\", \"%f\" ]", pos.getX(), pos.getY() );
    }
    else if (data.type() == Variant::Bool) // boolean value?
    {
      str = data.toBool() ? "true" : "false";
    }
    else if (data.type() == Variant::ULongLong) // large unsigned number?
    {
      str = StringHelper::format( 0xff, "%u", data.toULongLong() );
    }
    else if ( data.canConvert( Variant::LongLong ) ) // any signed number?
    {
      str = StringHelper::format( 0xff, "%d", data.toLongLong() );
    }
    else if (data.canConvert( Variant::Long ))
    {
      str = StringHelper::format( 0xff, "%d", data.toLongLong() );
    }
    else if (data.canConvert( Variant::String ) ) // can value be converted to string?
    {
      // this will catch Date, DateTime, Url, ...
      str = sanitizeString( data.toString() );
    }
    else
    {
      success = false;
    }

    if (success)
    {
            return str;
    }
    else
    {
      return std::string();
    }
}
コード例 #18
0
ファイル: issuers.cpp プロジェクト: mbarnhill/CreditMetrics
IssuerEntry::IssuerEntry(const vector<string>& cells) :
	name(sanitizeString(cells.at(0))),
	rating(sanitizeString(cells.at(1))),
	industry(sanitizeString(cells.at(2))),
	correl(convertDouble(cells.at(3)))
{}
コード例 #19
0
ファイル: menu.c プロジェクト: rudimeier/mprime
void test_primenet (void)
{
	int	m_primenet, m_dialup;
	unsigned long m_proxy_port, m_debug;
	char	m_userid[21], m_compid[21], m_proxy_host[121];
	char	m_proxy_user[51], m_proxy_pwd[51], orig_proxy_pwd[51];
	unsigned short proxy_port;
	int	update_computer_info, primenet_debug;
	char	m_username[81], m_userpwd[14];

	update_computer_info = FALSE;
	primenet_debug = IniSectionGetInt (INI_FILE, "PrimeNet", "Debug", 0);

	m_primenet = USE_PRIMENET;
	if (strcmp (USERID, "ANONYMOUS") == 0)
		m_userid[0] = 0;
	else
		strcpy (m_userid, USERID);
	strcpy (m_compid, COMPID);
	m_dialup = DIAL_UP;
	getProxyInfo (m_proxy_host, &proxy_port, m_proxy_user, m_proxy_pwd);
	m_proxy_port = proxy_port;
	strcpy (orig_proxy_pwd, m_proxy_pwd);
	m_debug = primenet_debug;

	askYN ("Use PrimeNet to get work and report results", &m_primenet);
	if (!m_primenet) goto done;

	outputLongLine ("\nYou must first create your user ID at mersenne.org or leave user ID blank to run anonymously.  See the readme.txt file for details.\n");
	askStr ("Optional user ID", m_userid, 20);
	askStr ("Optional computer name", m_compid, 20);

	askYN ("Computer uses a dial-up connection to the Internet", &m_dialup);

	askStr ("Optional proxy host name", m_proxy_host, 120);
	if (!m_proxy_host[0]) goto done;

	askNum ("Proxy port number", &m_proxy_port, 1, 65535);
	askStr ("Optional proxy user name", m_proxy_user, 50);
	askStr ("Optional proxy password", m_proxy_pwd, 50);
	askNum ("Output debug info to prime.log (0=none, 1=some, 2=lots)", &m_debug, 0, 2);

done:	if (askOkCancel ()) {
		DIAL_UP = m_dialup;
		IniWriteInt (INI_FILE, "DialUp", DIAL_UP);

		if (m_proxy_host[0] && m_proxy_port != 8080)
			sprintf (m_proxy_host + strlen (m_proxy_host), ":%lu", m_proxy_port);
		IniSectionWriteString (INI_FILE, "PrimeNet", "ProxyHost", m_proxy_host);
		if (m_proxy_host[0]) {
			IniSectionWriteString (INI_FILE, "PrimeNet", "ProxyUser", m_proxy_user);
			if (strcmp (m_proxy_pwd, orig_proxy_pwd)) {
				IniSectionWriteString (INI_FILE, "PrimeNet",
					"ProxyPass", m_proxy_pwd);
				IniSectionWriteInt (INI_FILE, "PrimeNet",
					"ProxyMask", 0);
			}
		}
		if (m_debug != primenet_debug) {
			IniSectionWriteInt (INI_FILE, "PrimeNet", "Debug",
					    m_debug);
		}

		if (m_userid[0] == 0)
			strcpy (m_userid, "ANONYMOUS");

		if (strcmp (USERID, m_userid) != 0) {
			strcpy (USERID, m_userid);
			sanitizeString (USERID);
			IniWriteString (INI_FILE, "V5UserID", USERID);
			update_computer_info = TRUE;
		}
		if (strcmp (COMPID, m_compid) != 0) {
			strcpy (COMPID, m_compid);
			sanitizeString (COMPID);
			IniWriteString (LOCALINI_FILE, "ComputerID", COMPID);
			update_computer_info = TRUE;
		}

		if (!USE_PRIMENET && m_primenet) {
			USE_PRIMENET = 1;
			create_window (COMM_THREAD_NUM);
			base_title (COMM_THREAD_NUM, "Communication thread");
			if (!STARTUP_IN_PROGRESS) set_comm_timers ();
			spoolMessage (PRIMENET_UPDATE_COMPUTER_INFO, NULL);
			spoolExistingResultsFile ();
		} else if (USE_PRIMENET && !m_primenet) {
			USE_PRIMENET = 0;
			if (!STARTUP_IN_PROGRESS) set_comm_timers ();
		} else if (update_computer_info)
			spoolMessage (PRIMENET_UPDATE_COMPUTER_INFO, NULL);

		IniWriteInt (INI_FILE, "UsePrimenet", USE_PRIMENET);
		spoolMessage (PRIMENET_PROGRAM_OPTIONS, NULL);
	} else
		STARTUP_IN_PROGRESS = 0;
}
コード例 #20
0
ファイル: json.cpp プロジェクト: binakot/caesaria-game
std::string Json::serialize(const Variant &data, bool &success, const std::string& tab)
{
  std::string str;
  success = true;

  if( data.isNull() ) // invalid or null?
  {
    return "null";
  }

  switch( data.type() )
  {
    case Variant::List:
    case Variant::NStringArray: // variant is a list?
    {
      StringArray values;
      const VariantList rlist = data.toList();
      std::string serializedValue;
      serializedValue.reserve( 512 );
      for( auto item : rlist )
      {
        serializedValue = serialize( item, "" );
        if( serializedValue.empty() )
        {
            success = false;
            break;
        }

        values.push_back( serializedValue );
      }

      str = "[ " + join( values, ", " ) + " ]";
    }
    break;

    case Variant::Map: // variant is a map?
    {
      VariantMap vmap = data.toMap();
      
      if( vmap.empty() )
      {
        str = "{}";
      }
      else
      {
        str = "{ \n";
        StringArray pairs;
        std::string serializedValue;
        serializedValue.reserve( 512 );
        for( auto item : vmap )
        {        
          serializedValue = serialize( item.second, tab + "  ");
          if( serializedValue.empty())
          {
                  //success = false;
            pairs.push_back( tab + sanitizeString( item.first ) + std::string( " : \"nonSerializableValue\"" ) );
            continue;
          }
          pairs.push_back( tab + sanitizeString( item.first ) + " : " + serializedValue );
        }
        str += join(pairs, ",\n");
        std::string rtab( tab );
        rtab.resize( std::max<int>( 0, tab.size() - 2 ) );
        str += std::string( "\n" ) + rtab + "}";
      }
    }
    break;

    case Variant::String:
    case Variant::NByteArray: // a string or a byte array?
    {
      str = sanitizeString( data.toString() );
    }
    break;

    case Variant::Double:
    case Variant::Float: // double?
    {
      // TODO: cheap hack - almost locale independent double formatting
      str = utils::format( 0xff, "\"%f\"", data.toDouble() );
      str = utils::replace(str, ",", ".");
      if( str.find(".") == std::string::npos && str.find("e") == std::string::npos )
      {
         str += ".0";
      }
    }
    break;

    case Variant::NTilePos:
    {
      const TilePos& pos = data.toTilePos();
      str = utils::format( 0xff, "[ %d, %d ]", pos.i(), pos.j() );
    }
    break;

    case Variant::NSize:
    {
      const Size& size = data.toSize();
      str = utils::format( 0xff, "[ %d, %d ]", size.width(), size.height() );
    }
    break;

    case Variant::NPoint:
    {
      const Point& pos = data.toPoint();
      str = utils::format( 0xff, "[ %d, %d ]", pos.x(), pos.y() );
    }
    break;

    case Variant::NPointF:
    {
      PointF pos = data.toPointF();
      // TODO: cheap hack - almost locale independent double formatting
      std::string posX = utils::replace(utils::format( 0xff, "%f", pos.x()), ",", ".");
      std::string posY = utils::replace(utils::format( 0xff, "%f", pos.y()), ",", ".");
      str = utils::format( 0xff, "[ \"%s\", \"%s\" ]", posX.c_str(), posY.c_str() );
    }
    break;

    case Variant::Bool: // boolean value?
    {
      str = data.toBool() ? "true" : "false";
    }
    break;

    case Variant::ULongLong: // large unsigned number?
    {
      str = utils::format( 0xff, "%u", data.toULongLong() );
    }
    break;

    case Variant::Int: // simple int?
    {
      str = utils::format( 0xff, "%d", data.toInt() );
    }
    break;

    case Variant::UInt:
    {
      str = utils::format( 0xff, "%d", data.toInt() );
    }
    break;

    default:
      if ( data.canConvert( Variant::LongLong ) ) // any signed number?
      {
        str = utils::format( 0xff, "%d", data.toLongLong() );
      }
      else if (data.canConvert( Variant::Long ))
      {
        str = utils::format( 0xff, "%d", data.toLongLong() );
      }
      else if (data.canConvert( Variant::String ) ) // can value be converted to string?
      {
        // this will catch Date, DateTime, Url, ...
        str = sanitizeString( data.toString() );
      }
      else
      {
        success = false;
      }
    break;
  }

  return success ? str : std::string();
}
コード例 #21
0
ファイル: serverdatabase.cpp プロジェクト: darthvid/sion
/**
 * Adds a new (unique) file attribute pair (name/value) to the db
 *
 * @param fileId is the file id
 * @param attrName is the name of the file attribute
 * @param attrValue is the value of the file attribute
 */
void ServerDatabase::addFileAttribute(QString fileId, QString attrName, QString attrValue) {
    m_dbSem.acquire();

    QSqlQuery query(m_db);

    sanitizeString(attrName);
    sanitizeString(attrValue);

#ifdef _VERBOSE_DATABASE
        qDebug() << "adding file attribute " << fileId << "/" << attrName;
#endif

    // insert tuple filepath/attrName
#ifdef _INSERT_UPDATE_ATTRIBUTE
    if (!query.exec("INSERT INTO attributes(file_id, attribute_name, attribute_value) VALUES(" + fileId + ", '" + attrName + "', '" + attrValue + "') ON DUPLICATE KEY UPDATE attribute_value='" + attrValue + "'")) {
#else
    query.exec("DELETE FROM attributes WHERE file_id=" + fileId + " AND attribute_name='" + attrName + "'");
    if (!query.exec("INSERT INTO attributes(file_id, attribute_name, attribute_value) VALUES(" + fileId + ", '" + attrName + "', '" + attrValue + "')")) {
#endif
        qDebug() << QObject::tr("Failed to insert into attributes table in DB ") + DB_NAME + QObject::tr(" on host ") + DB_HOST + QObject::tr(" with usr/pwd ") + DB_USR + "/" + DB_PWD;
        qDebug() << QObject::tr("ERROR: ") + query.lastError().text();
    }

    m_dbSem.release();
}

/**
 * Gets all file references from the db for a given filter.
 *
 * @param filterId is the filter id
 */
QStringList ServerDatabase::getFiles(QString filterId) {
    m_dbSem.acquire();

    QStringList result;

    QSqlQuery query(m_db);

#ifdef _VERBOSE_DATABASE
        qDebug() << "retrieving files for " << filterId;
#endif

    // get files
    if (!query.exec("SELECT path FROM files WHERE filter_id=" + filterId)) {
        qDebug() << QObject::tr("Failed to query from files table in DB ") + DB_NAME + QObject::tr(" on host ") + DB_HOST + QObject::tr(" with usr/pwd ") + DB_USR + "/" + DB_PWD;
        qDebug() << QObject::tr("ERROR: ") + query.lastError().text();
    } else {
        while (query.next()) {
            QString filepath = query.value(0).toString();
            unsanitizeString(filepath);

#ifdef _VERBOSE_DATABASE
            qDebug() << "retrieved file for " << filterId << ": " << filepath;
#endif
            result += filepath;
        }
    }

    m_dbSem.release();

    return result;
}
コード例 #22
0
void JsonSerializer::addString(const QString &string) {
  m_buffer.append("\"");
  m_buffer.append(sanitizeString(string));
  m_buffer.append("\"");
}