Exemplo n.º 1
0
PhDebug::PhDebug()
{
	qInstallMessageHandler(this->messageOutput);

#if defined(Q_OS_MAC)
	QString logDirPath = QDir::homePath() + "/Library/Logs/Phonations/";
#elif defined(Q_OS_WIN)
	QString logDirPath = QString(qgetenv("APPDATA")) + "/Phonations";
#else
#error Choose a folder for log
#endif

	QDir logDir(logDirPath);
	if(!logDir.exists()) {
		QDir().mkdir(logDirPath);
	}
	_logFileName = logDirPath + APP_NAME + ".log";
	QFile * f = new QFile(_logFileName);
	f->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append);
	f->write("\n\n");
	_textLog = new QTextStream(f);

	_displayDate = false;
	_displayTime = true;
	_displayFunctionName = true;
	_displayFileName = true;
	_displayLine = true;
	_showConsole = true;
	_logMask = 1;
}
Exemplo n.º 2
0
/* on_backupButton_clicked()
 * Called : When User Clicks Backup Button
 * Performs : Bakeup of Log
 */
void Settings::on_backupButton_clicked()
{
    if(logPathLE->text().isEmpty())
        return;
    directory=logPathLE->text()+"DocmaQ Log Backup/";
    QStringList logpath,logdir;
    QString path,dir;
    logpath<<"./logs/certificate/"<<"./logs/session/";
    logdir<<"certificate"<<"session";
    int q=0;

    for(int k=0;k<2;k++)
    {
        path=logpath[k];
        dir=logdir[k];

        QDir logDir(path);

        QStringList files = logDir.entryList(QStringList("*.Log"),QDir::Files,QDir::Time|QDir::Reversed);
        uint size=files.count();

        if(!QDir(directory+dir).exists())
        {
            QDir().mkdir(directory);
            //create a directory if dir doesn't exist
            QDir().mkdir(directory+dir);
        }

        QProgressDialog progressDialog(this);
        progressDialog.setCancelButtonText(tr("&Cancel"));
        progressDialog.setRange(0, size);
        progressDialog.setWindowTitle(tr("Performing Back Up....      "));
        progressDialog.show();

        for (uint i=0;i<size;i++)
        {
            q=1;
            progressDialog.setValue(i);
            progressDialog.setLabelText(tr("Back up file %1 of %2...\n\nCurrent File: %3")
                                        .arg(i).arg(size).arg(files[i]));
            qApp->processEvents();

            if (progressDialog.wasCanceled())
                break;
            if(!createServerFile( files[i],path,dir))
            {
                k=1;//to stop back up of session logs incase of failure with certificate logs
                break;
            }
        }
    }

    if(QFile().error()==QFile::CopyError)
        QMessageBox::information(this,tr("DocmaQ Log Manager"),tr("Back Up failed due to an error.\n\nOperation Aborted !!"),QMessageBox::Ok);
    else
    {
        if(q==1)
            QMessageBox::information(this,tr("DocmaQ Log Manager"),tr("Back Up Successful !!"),QMessageBox::Ok);
    }
}
Exemplo n.º 3
0
void ChatWindow::cdIntoLogPath()
{
    QString home = KUser(KUser::UseRealUserID).homeDir();
    QUrl logUrl = Preferences::self()->logfilePath();

    if(!logUrl.isLocalFile())
    {
        return;
    }

    QString logPath = logUrl.toLocalFile();

    QDir logDir(home);

    // Try to "cd" into the logfile path.
    if (!logDir.cd(logPath))
    {
        // Only create log path if logging is enabled.
        if (log())
        {
            // Try to create the logfile path and "cd" into it again.
            logDir.mkpath(logPath);
            logDir.cd(logPath);
        }
    }

    // Add the logfile name to the path.
    logfile.setFileName(logDir.path() + '/' + logName);
}
void AbstractGeneratorConfig::configureLogging()
{
    if (getString("application.output-type") != "socket")
    {
        // log-path
        File logPath(getString("application.log-path"));
        if (logPath.exists())
        {
            logPath.remove(true);
        }
        File logDir(Path(getString("application.log-path")).parent());
        logDir.createDirectories();

        // create the formatting file channel
        Formatter* simpleFileFormatter = new PatternFormatter("%t");
        _loggerFormattersPool.add(simpleFileFormatter);
        Channel* simpleFileChannel = new SimpleFileChannel(getString("application.log-path"));
        _loggerChannelsPool.add(simpleFileChannel);
        Channel* formattingChannel = new FormattingChannel(simpleFileFormatter, simpleFileChannel);
        _loggerChannelsPool.add(formattingChannel);
        // configure the formatting file channel
        Logger::root().setChannel(formattingChannel);
        _logger.setChannel(formattingChannel);
    }
}
Exemplo n.º 5
0
bool lmcTraceInit(
    LmcTraceMode tMode,
    QString logdir,
    QString strLogFileName )
{

    g_traceMode = DoNotTrace;
    g_logFileName.clear();

    if ( logdir.isEmpty() )
        return false;

    if ( strLogFileName.isEmpty() )
        return false;

    g_traceMode = tMode;

    // log directory
    QDir logDir( logdir );
    if( ! logDir.exists() )
        logDir.mkdir( logDir.absolutePath() );

    // log file name
    g_logFileName = strLogFileName;

    lmctrace(
        "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n" \
        "                          application log\n" \
        "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"  );

    return true;
}
Exemplo n.º 6
0
void DiskUtil::appendToLogFile(const QString &fileName, const QString &line) {

    static QDate today = QDate::currentDate();
    static QMap<QString, QFile *> openFiles;

    if (today != QDate::currentDate()) {
        for (QFile *file : openFiles) {
            file->close();
            delete file;
        }
        openFiles.clear();
        today = QDate::currentDate();
    }

    QFile *file;
    if (openFiles.contains(fileName)) {
        file = openFiles[fileName];
    } else {
        QString dirPath = logDir() + "/" + today.toString("yyyyMMdd");
        if (!QDir(dirPath).exists() && !QDir(logDir()).mkpath(today.toString("yyyyMMdd"))) {
            LogUtil::setLoggingEnabled(false);
            LogUtil::logError("Could not create log directory: %1\n"
                              "Logging system disabled.", dirPath);
            return;
        }

        QString path = dirPath + "/" + fileName;
        file = new QFile(path);
        if (!file->open(QIODevice::WriteOnly | QIODevice::Append)) {
            LogUtil::setLoggingEnabled(false);
            LogUtil::logError("Could not open log file: %1\n"
                              "Logging system disabled.", path);
            return;
        }

        openFiles[fileName] = file;
    }

    file->write(QString(QTime::currentTime().toString("HH:mm:ss.zzz ") + line + "\n").toUtf8());
    file->flush();
}
Exemplo n.º 7
0
Logger::Logger() : m_debugLevel(QtCriticalMsg)
{
#ifndef __APPLE__
    m_logfileName = QDir::tempPath();
#else
    m_logfileName = QDir::homePath () + "/Library/Logs/Avalon";
    QDir logDir(m_logfileName);
    qDebug() << logDir.absolutePath();
    logDir.mkpath(logDir.absolutePath());
#endif
    m_logfileName += "/avalon_" +
            QDateTime::currentDateTime().toString(Qt::ISODate) + ".log";
}
Exemplo n.º 8
0
	FileAppender::FileAppender() {
		ptree config;
		read_xml("conf/config.xml", config, trim_whitespace && no_comments && no_concat_text);
		fs::path logFile = fs::path(config.get<string>("blacksunConfig.logging.logFile.<xmltext>"));
		fs::path logDir(logFile);
		logDir = logDir.remove_filename();

		if(!fs::exists(logDir)) {
			fs::create_directories(logDir);
		}

		stream = new fs::ofstream(logFile, std::ios_base::app);
	}
Exemplo n.º 9
0
/** Запускает приложение */
int
launchApp(int argc, char *argv[])
{
#ifdef Q_WS_X11
	XInitThreads();
#endif
	QApplication app(argc, argv);

#ifdef Q_OS_WIN
	QApplication::setStyle(new SalonStyle);
#endif

	QTextCodec *codec = QTextCodec::codecForName("UTF-8");
	QTextCodec::setCodecForTr(codec);
	QTextCodec::setCodecForCStrings(codec);
	QTextCodec::setCodecForLocale(codec);


	QLocale::setDefault(QLocale(QLocale::Russian, QLocale::RussianFederation));

	QDir logDir(QDir::tempPath());
	if (logDir.exists())
	{
		logFile.setFileName(logDir.absolutePath() + QDir::separator() + "salon.log");
		logFile.open(QIODevice::WriteOnly | QIODevice::Append);
	}
	qInstallMsgHandler(messageHandler);

	if (!DBService::getInstance()->getConnection()->isConnected())
	{
		QMessageBox::critical(NULL, "Ошибка БД", "Нет соединения с БД");
		exit(0);
	}

	LoginDialog login;
	if (login.exec() == false)
	{
		exit(0);
	}

	qRegisterMetaType<ClientItem*>("ClientItem*");
	qRegisterMetaType<Item*>("Item*");
	qRegisterMetaType< QList<ClientItem*> >("QList<ClientItem*>");
	qRegisterMetaType< QList<Item*> >("QList<Item*>");
	ClientPanel mainPanel;
	mainPanel.showMaximized();

	qDebug() << QSqlDatabase::drivers();

	return app.exec();
}
Exemplo n.º 10
0
// Create a directory for all logging output of this simulation
// Format:  /POSSIM_home/yyyy_mm_dd/hh_mm_ss
void Logging::createDir() {
    time_t rawtime;
    struct tm *t;
    std::string dirName;
    
    boost::filesystem::path logDir("logs");
    boost::filesystem::create_directory(logDir);
    
    // Create logs directory
    //if(stat("logs",&st) != 0)
    //    system("mkdir logs");

    // Create directory for this date
    time(&rawtime);
    t = localtime(&rawtime);
    dirName = "logs/" + utility::time2string(t->tm_year+1900) + "_" 
                      + utility::time2string(t->tm_mon+1) + "_"
                      + utility::time2string(t->tm_mday);
    //if(stat(dirName.c_str(),&st) != 0)
    //    system((std::string("mkdir ")+dirName).c_str());
    boost::filesystem::path dateDir(dirName);
    boost::filesystem::create_directory(dateDir);
    
    // Create directory for this run
    dirName = dirName + "/" + utility::time2string(t->tm_hour) + "_"
                            + utility::time2string(t->tm_min) + "_"
                            + utility::time2string(t->tm_sec);

    // Make sure directory is unique even if time matches a previously created dir
//    if(stat(dirName.c_str(),&st) != 0) {
    boost::filesystem::path timeDir(dirName);

    if(!boost::filesystem::exists(timeDir)) {
        //system((std::string("mkdir ")+dirName).c_str());
        boost::filesystem::create_directory(timeDir);
        directory = dirName + "/";
    }
    else {
        int index = 2;
        std::string newDirName = dirName + "_" + utility::int2string(index);
        
        timeDir = newDirName;
        while(boost::filesystem::exists(timeDir)) {
            index++;
            timeDir = dirName + "_" + utility::int2string(index);
        }
        //system((std::string("mkdir ")+newDirName).c_str());
        boost::filesystem::create_directory(timeDir);
        directory = newDirName + "/";
    }
}
Exemplo n.º 11
0
void Logger::openLog(const QString &APath)
{
	QMutexLocker locker(&FMutex);
	LoggerData *q = instance()->d;
	if (!q->logFile.isOpen() && !APath.isEmpty())
	{
		QDir logDir(APath);
		QStringList logFiles = logDir.entryList(QStringList()<<"*.log",QDir::Files,QDir::Name);
		while (logFiles.count() > MAX_LOG_FILES)
			QFile::remove(logDir.absoluteFilePath(logFiles.takeFirst()));

#ifndef DEBUG_MODE
		qInstallMsgHandler(qtMessagesHandler);
#endif
		q->logFile.setFileName(logDir.absoluteFilePath(DateTime(QDateTime::currentDateTime()).toX85DateTime().replace(":","-") +".log"));
		q->logFile.open(QFile::WriteOnly|QFile::Truncate);
	}
}
Exemplo n.º 12
0
/**
 * @brief This is the reload member. The operation written here, are executed every time this page is shown.
 */
void alarms_history::reload()
{
    /* clear the old value */
    ui->listWidget->clear();
    
    /* get the file list */
    QDir logDir(ALARMS_DIR);
    logFileList = logDir.entryList(QDir::Files|QDir::NoDotAndDotDot, QDir::Reversed);
    
    ui->comboBoxDate->clear();
    
    for (int i = 0; i < logFileList.count(); i++)
    {
        if (logFileList.at(i).endsWith(".log") == false)
        {
            logFileList.removeAt(i);
            i--;
        }
        else
        {
            ui->comboBoxDate->addItem(QDate().fromString(logFileList.at(i),"yyyy_MM_dd.log").toString("yyyy/MM/dd"));
        }
    }
    
    _current = 0;
    _alarm = true;
    _event = true;
    _level = level_all_e;
    
    /* no logfile found */
    _file_nb = logFileList.count();
    if (_file_nb == 0)
    {
        LOG_PRINT(error_e, "No file to load\n");
        return;
    }
    
    /* load the current log file */
    LOG_PRINT(info_e, "_current %d\n",_current);
    ui->comboBoxDate->setCurrentIndex(_current);
    loadLogFile(_current, _alarm, _event, _level);
}
Exemplo n.º 13
0
QString FileUtils::standardPath(QString subfolder) {
    // standard path
    // Mac: ~/Library/Application Support/Interface
#ifdef Q_OS_ANDROID
    QString path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
#else
    QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
#endif
    if (!subfolder.startsWith("/")) {
        subfolder.prepend("/");
    }
    if (!subfolder.endsWith("/")) {
        subfolder.append("/");
    }
    path.append(subfolder);
    QDir logDir(path);
    if (!logDir.exists(path)) {
        logDir.mkpath(path);
    }
    return path;
}
Exemplo n.º 14
0
static void openCurrentLogFiles() {
    time_t t = time( NULL );
    struct tm *timeStruct = localtime( &t );
    
    char fileName[100];

    File logDir( NULL, "curseLog" );
    
    if( ! logDir.exists() ) {
        Directory::makeDirectory( &logDir );
        }

    if( ! logDir.isDirectory() ) {
        AppLog::error( "Non-directory curseLog is in the way" );
        return;
        }

    strftime( fileName, 99, "%Y_%m%B_%d_%A.txt", timeStruct );
    
    File *newFile = logDir.getChildFile( fileName );
    
    char *newFileName = newFile->getFullFileName();
    
    logFile = fopen( newFileName, "a" );

    delete newFile;
    
    if( logFile == NULL ) {
        AppLog::errorF( "Failed to open log file %s", newFileName );
        delete [] newFileName;

        return;
        }

    // only set these if opened successfully
    currentYear = timeStruct->tm_year;
    currentDay = timeStruct->tm_yday;    

    delete [] newFileName;
    }
Exemplo n.º 15
0
void Server::updateNextSession()
{
  sessionUpdateTimer.stop();
  group->SetLogDir(NULL);

  if (config->logPath.Get()[0] == '\0') {
    return;
  }

  if (group->numAuthenticatedUsers() < 2) {
    return;
  }

  QDir logDir(config->logPath.Get());
  QString sessionPath;
  int cnt;
  for (cnt = 0; cnt < 16; cnt++) {
    QString sessionName = QDateTime::currentDateTime().toString("yyyyMMdd_hhmm");
    if (cnt > 0) {
      sessionName += QString("_%1").arg(cnt);
    }
    sessionName += ".wahjam";

    sessionPath = logDir.absoluteFilePath(sessionName);
    if (logDir.mkdir(sessionName)) {
      break;
    }
  }

  if (cnt < 16 )
  {
    group->SetLogDir(sessionPath.toLocal8Bit().constData());
    setActiveSessionUpdateTimer();
  }
  else
  {
    qWarning("Error creating a session archive directory! Gave up after '%s' failed!",
             sessionPath.toLatin1().constData());
  }
}
Exemplo n.º 16
0
bool Init()
{
    boost::filesystem::path logDir(GET_CONFIG_ELEMENT_STR("LOG_LOCATION"));
    if (!boost::filesystem::exists(logDir))
    {
        if (!boost::filesystem::create_directory(logDir))
            return false;
    }


    //the name of the file will be the data added to the time
    std::stringstream ss;

    time_t t = time(0);
    struct tm * now = localtime(&t);
    ss << GET_CONFIG_ELEMENT_STR("LOG_LOCATION") << now->tm_mon + 1 << "." << now->tm_mday << "." << now->tm_year + 1900 << " " << now->tm_hour + 1 << "-" << now->tm_min << "-" << now->tm_sec << ".log";

    gLog.open(ss.str().c_str());
    gLog << "=====================\tHeader\t=====================\n";

    return true;
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
    // Setup Signal Handler, to exit gracefully on an INT signal
    signal(SIGINT, *sighandler);

    CONDITION
	cond;
    DUL_NETWORKKEY
	* network = NULL;
    DUL_ASSOCIATIONKEY
	* association = NULL;
    DUL_ASSOCIATESERVICEPARAMETERS *service;
    DUL_PRESENTATIONCONTEXT
	* requestedCtx;
    DUL_ABORTITEMS
	abortItems;

    MFileOperations f;
    char path[256];
    f.expandPath(path, "MESA_TARGET", "logs");
    MString logDir(path);            // Default is Storage Area
    f.expandPath(path, "MESA_STORAGE", "postproc");
    MString storageDir(path);            // Default is Storage Area
    char *dbName = "ppwf";            // Default database nameea

    int
        port,
        trips = 2048,		/* Trips through the main loop */
        classCount = 0,
        releaseDelay = 0,
        numBase = 100;		// msg number base for logging
    unsigned long
        maxPDU = 16384;
    CTNBOOLEAN
	verboseDUL = FALSE,
	verboseSRV = FALSE,
	verboseDCM = FALSE,
	abortFlag = FALSE,
	forgiveFlag = FALSE,
	forkFlag = FALSE,
	threadFlag = FALSE,
	paramsFlag = FALSE,
	acceptFlag,
	drop,
	done = FALSE,
	printConnectionStatistics = FALSE;
    DUL_SC_ROLE
	scRole;
    int associationRequests = 0;

    char *classArray[] = {
	DICOM_SOPCLASSVERIFICATION,
	DICOM_SOPGPWORKLIST_FIND,
	DICOM_SOPGPSPS,
	DICOM_SOPGPPPS,
    ""};

    char *serverTitle = POST_PROC_AE_TITLE;
    MLogClient::LOGLEVEL logLevel = MLogClient::MLOG_NONE;
    int fileMode = 0;
   
    while (--argc > 0 && (*++argv)[0] == '-') {
      int l1 = 0;
	switch (*(argv[0] + 1)) {
	case 'a':
	   argc--; argv++;
	   if (argc < 1)
	     usageerror();
	   logDir = MString(*argv);
	   break;
	case 'b':
	   argc--; argv++;
	   if (argc < 1)
	     usageerror();
	   if (sscanf(*argv, "%d", &numBase) != 1)
	     usageerror();
	   break;
	case 'c':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    serverTitle = *argv;
	    break;
	case 'd':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    if (strcmp(*argv, "DCM") == 0)
		verboseDCM = TRUE;
	    else if (strcmp(*argv, "DUL") == 0)
		verboseDUL = TRUE;
	    else if (strcmp(*argv, "SRV") == 0)
		verboseSRV = TRUE;
	    else
		usageerror();
	    break;
	case 'f':
	    forkFlag = TRUE;
	    break;
	case 'i':
	    forgiveFlag = TRUE;
	    break;
	case 'j':
#ifndef CTN_USE_THREADS
	    fprintf(stderr, "pp_dcmps was not compiled with threads\n");
	    return 1;
#else
	    //threadFlag = TRUE;
	    break;
#endif
	case 'l':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    if (sscanf(*argv, "%d", &l1) != 1)
		usageerror();
	    logLevel = (MLogClient::LOGLEVEL)l1;
	    break;
	case 'm':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    if (sscanf(*argv, "%lu", &maxPDU) != 1)
		usageerror();
	    break;
	case 'n':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    dbName = *argv;
	    break;
	case 'p':
	    paramsFlag = TRUE;
	    break;
	case 't':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    if (sscanf(*argv, "%d", &trips) != 1)
		usageerror();
	    break;
	case 'v':
	    verboseDUL = TRUE;
	    verboseSRV = TRUE;
	    break;
	case 'y':
	    printConnectionStatistics = TRUE;
	    break;
	case 'z':
	    fileMode++;
	    break;
	default:
	    (void) fprintf(stderr, "Unrecognized option: %c\n", *(argv[0] + 1));
	    break;
	}
    }

    if (argc < 1)
	usageerror();

    // If in filemode, perform the query and exit
    if (fileMode) {
      ppwlQuery (*argv, logDir, numBase, dbName);
      return 0;
    }
    
    // Write PID file
    MServerAgent a("pp_dcmps");
    a.registerServerPID();

    if (sscanf(*argv, "%d", &port) != 1)
      usageerror();

    checkEnvironment();

    ::THR_Init();

    ::DCM_Debug(verboseDCM);
    ::DUL_Debug(verboseDUL);
    ::SRV_Debug(verboseSRV);

#ifndef _MSC_VER
    if (port < 1024) {
	if (geteuid() != 0) {
	    char errmsg[] =
	    "To use this port (%d), you must run as root or the application must be\n\
setuid root (see chmod)\n";

	    fprintf(stderr, errmsg, port);
	    perror("");
	    exit(1);
	}
    }
#endif

    if (logLevel != MLogClient::MLOG_NONE) {
      MLogClient logClient;
      logClient.initialize(logLevel, logDir + "/pp_dcmps.log");

      logClient.log(MLogClient::MLOG_ERROR,
		    "<no peer>", "pp_dcmps<main>", __LINE__,
		    "Begin server process");
      cout << "pp_dcmps logging messages at level "
	   << logLevel
	   << " to "
	   << logDir + "/pp_dcmps.log"
	   << endl;
    }

    cond = ::DUL_InitializeNetwork(DUL_NETWORK_TCP, DUL_AEBOTH,

		 (void *) &port, DUL_TIMEOUT, DUL_ORDERBIGENDIAN, &network);
    if (cond != DUL_NORMAL) {
	::COND_DumpConditions();
	::exit(1);
    }
/*  Go back to the proper uid so we don't mess with things we don't own.
*/

#ifndef _MSC_VER
    (void) setuid(getuid());
#endif

    done = FALSE;
    while (!done) {
	drop = FALSE;
	service = (DUL_ASSOCIATESERVICEPARAMETERS*)malloc(sizeof(*service));
	if (service == NULL) {
	    ::fprintf(stderr, "Could not allocate memory for association parameters\n");
	    ::exit(1);
	}
	(void) ::memset(service, 0, sizeof(*service));
	service->maxPDU = maxPDU;
	strcpy(service->calledImplementationClassUID,
	       MIR_IMPLEMENTATIONCLASSUID);
	strcpy(service->calledImplementationVersionName,
	       MIR_IMPLEMENTATIONVERSIONNAME);
	cond = ::DUL_ReceiveAssociationRQ(&network, DUL_BLOCK,
					service, &association);
	{
	  MLogClient logClient;
	  logClient.log(MLogClient::MLOG_CONVERSATION,
		    service->callingAPTitle,
			"pp_dcmps<main>", __LINE__,
			"Association Request");
	}

	acceptFlag = TRUE;
	if (cond != DUL_NORMAL) {
	    ::COND_DumpConditions();
	    if (cond == DUL_UNSUPPORTEDPEERPROTOCOL) {
		acceptFlag = FALSE;
		cond = APP_NORMAL;	/* Yes, this is normal */
	    } else
		::exit(0);
	}
	if (acceptFlag) {
	    cond = associationCheck(service, serverTitle,
				    forgiveFlag, &abortItems);
	    if (CTN_ERROR(cond)) {
		acceptFlag = FALSE;
		::fprintf(stderr, "Incorrect Association Request\n");
		::COND_DumpConditions();
		cond = ::DUL_RejectAssociationRQ(&association, &abortItems);
		if (cond != DUL_NORMAL) {
		    ::fprintf(stderr, "Unable to cleanly reject Association\n");
		    ::COND_DumpConditions();
		}
	    } else if (!CTN_SUCCESS(cond)) {
		::COND_DumpConditions();
	    }
	}
	if (acceptFlag) {
	    if (verboseDUL || paramsFlag) {
		fprintf(stdout,
			"Application is about to accept association.  The association parameters\n\
before the app has decided which presentation contexts to accept follow.\n");
		::DUL_DumpParams(service);
	    }
	    requestedCtx = (DUL_PRESENTATIONCONTEXT*)::LST_Head(&service->requestedPresentationContext);
	    if (requestedCtx != NULL)
		(void) ::LST_Position(&service->requestedPresentationContext,
				    requestedCtx);
	    classCount = 0;
	    while (requestedCtx != NULL) {
		if (strcmp(requestedCtx->abstractSyntax, MIR_SOPCLASSKILLSERVER) == 0)
		    done = TRUE;

		if (supportedClass(requestedCtx->abstractSyntax, classArray)) {
		    switch (requestedCtx->proposedSCRole) {
		    case DUL_SC_ROLE_DEFAULT:
			scRole = DUL_SC_ROLE_DEFAULT;
			break;
		    case DUL_SC_ROLE_SCU:
			scRole = DUL_SC_ROLE_SCU;
			break;
		    case DUL_SC_ROLE_SCP:
			scRole = DUL_SC_ROLE_DEFAULT;
			break;
		    case DUL_SC_ROLE_SCUSCP:
			scRole = DUL_SC_ROLE_SCU;
			break;
		    default:
			scRole = DUL_SC_ROLE_DEFAULT;
			break;
		    }
		    cond = ::SRV_AcceptServiceClass(requestedCtx, scRole,
						  service);
		    if (cond == SRV_NORMAL) {
			classCount++;
		    } else {
			::printf("SRV Facility rejected SOP Class: %s\n",
			       requestedCtx->abstractSyntax);
			::COND_DumpConditions();
		    }
		} else {
		    ::printf("Simple server rejects SOP Class with UID: %s\n",
			   requestedCtx->abstractSyntax);
		    dumpUIDDescription(requestedCtx->abstractSyntax);
		    cond = ::SRV_RejectServiceClass(requestedCtx,
				     DUL_PRESENTATION_REJECT_USER, service);
		    if (cond != SRV_NORMAL) {
			drop = TRUE;
		    }
		}
		requestedCtx = (DUL_PRESENTATIONCONTEXT*)::LST_Next(&service->requestedPresentationContext);
	    }
#if 0
	    ::printf("Supported classes: %d\n", classCount);
#endif
	    if (paramsFlag) {
		::fprintf(stdout,
			"Application has now decided which presentation contexts to accept.\n\
Association parameters now look like this.\n");
		::DUL_DumpParams(service);
	    }
	    if (drop) {
		(void) ::DUL_DropAssociation(&association);
		::COND_DumpConditions();
	    } else {
		if (printConnectionStatistics) {
		    printf("%6d: %16s %16s %s\n",
			   ++associationRequests,
			   service->calledAPTitle,
			   service->callingAPTitle,
			   service->callingPresentationAddress);
		}
		acceptManageAssociation(&network, association, service,
					forkFlag, threadFlag, abortFlag,
				verboseDUL, releaseDelay,
					logDir.strData(),
					storageDir.strData(),
                                        dbName );

	    }
	}
#if 0
	(void) ::DUL_ClearServiceParameters(service);
#endif
	if (CTN_ERROR(cond))
	    done = TRUE;
	if (trips >= 0) {
	    if (trips-- <= 0)
		done = TRUE;
	}
    }
Exemplo n.º 18
0
// FIXME: this currently does not work if the user has changed his date format,
// since . is hardcoded as date parts separator.
void KviQueryWindow::pasteLastLog()
{
	QString szQuery = target().toLower();
	QString szNetwork = console()->currentNetworkName().toLower();
	QDate date = QDate::currentDate();

	// Create the filter for the dir
	// Format: query__<nick>.<network>_*.*.*.log*
	QString szLogFilter = "query_";
	szLogFilter += szQuery;
	szLogFilter += ".";
	szLogFilter += szNetwork;
	szLogFilter += "_*.*.*.log*";

	// Get the logs
	QString szLogPath;
	g_pApp->getLocalKvircDirectory(szLogPath,KviApplication::Log);
	QDir logDir(szLogPath);
	QStringList filter = QStringList(szLogFilter);
	QStringList logList = logDir.entryList(filter,QDir::Files,QDir::Name | QDir::Reversed);

	// Scan log files
	// Format: query_nick.networkName_year.month.day.log
	// Format: query_nick.networkName_year.month.day.log.gz
	bool bGzip;
	QString szFileName;

	for(QStringList::Iterator it = logList.begin(); it != logList.end(); ++it)
	{
		int iLogYear, iLogMonth, iLogDay;

		szFileName = (*it);
		QString szTmpName = (*it);
		QFileInfo fi(szTmpName);
		bGzip = false;

		// Skip the log just created on join
		if(fi.suffix() == "tmp")
			continue;

		// Remove trailing dot and extension .gz
		if(fi.suffix() == "gz")
		{
			bGzip = true;
			szTmpName.chop(3);
		}

		// Ok, we have the right nick/network log. Get date
		QString szLogDate = szTmpName.section('.',-4,-1).section('_',1,1);
		iLogYear = szLogDate.section('.',0,0).toInt();
		iLogMonth = szLogDate.section('.',1,1).toInt();
		iLogDay = szLogDate.section('.',2,2).toInt();

		// Check log validity
		int iInterval = -KVI_OPTION_UINT(KviOption_uintDaysIntervalToPasteOnQueryJoin);
		QDate logDate(iLogYear,iLogMonth,iLogDay);
		QDate checkDate = date.addDays(iInterval);

		if(logDate < checkDate)
			return;
		else
			break;
	}

	// Get the right log name
	szFileName.prepend("/");
	szFileName.prepend(szLogPath);

	// Load the log
	QByteArray log = loadLogFile(szFileName,bGzip);
	if(log.size() > 0)
	{
		QList<QByteArray> list = log.split('\n');
		unsigned int uCount = list.size();
		unsigned int uLines = KVI_OPTION_UINT(KviOption_uintLinesToPasteOnQueryJoin);
		unsigned int uStart = uCount - uLines - 1;
/*
		// Check if the log is smaller than the lines to print
		if(uStart < 0)
			uStart = 0;
*/
		QString szDummy = __tr2qs("Starting last log");
		output(KVI_OUT_QUERYPRIVMSG,szDummy);

		// Scan the log file
		for(unsigned int i = uStart; i < uCount; i++)
		{
			QString szLine = QString(list.at(i));
			szLine = szLine.section(' ',1);
#ifdef COMPILE_ON_WINDOWS
			// Remove the \r char at the szEnd of line
			szLine.chop(1);
#endif
			// Print the line in the channel buffer
			output(KVI_OUT_QUERYPRIVMSG,szLine);
		}

		szDummy = __tr2qs("End of log");
		output(KVI_OUT_QUERYPRIVMSG,szDummy);
	}
}
Exemplo n.º 19
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
std::string Environment::logFile(const std::string& name) const
{
	return logDir() + "/" + Util::removeExtension(Util::basename(name)) + ".log";
}
Exemplo n.º 20
0
int main(int argc, char *argv[])
{

    // Uncomment next section to have memory leaks information
    // tracing in VC++ debug mode under Windows
/*
#if defined(_MSC_VER) && defined(_DEBUG)
    _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
*/

    Q_INIT_RESOURCE(OpenBoard);

    qInstallMsgHandler(ub_message_output);

#if defined(Q_WS_X11)
    qDebug() << "Setting GraphicsSystem to raster";
    QApplication::setGraphicsSystem("raster");
#endif

    UBApplication app("OpenBoard", argc, argv);

    //BUGFIX:
    //when importing a OpenBoard file that contains a non standard character
    //the codecForLocale or the codecForCString is used to convert the file path
    //into a const char*. This is why in french windows setup the codec name shouldn't be
    //set to UTF-8. For example, setting UTF-8, will convert "Haïti" into "HaÂ-ti.

    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    //QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

    QStringList args = app.arguments();

    QString dumpPath = UBSettings::userDataDirectory() + "/log";
    QDir logDir(dumpPath);
    if (!logDir.exists())
        logDir.mkdir(dumpPath);

    QString fileToOpen;

    if (args.size() > 1) {
        // On Windows/Linux first argument is the file that has been double clicked.
        // On Mac OSX we use FileOpen QEvent to manage opening file in current instance. So we will never
        // have file to open as a parameter on OSX.

        QFile f(args[1]);

        if (f.exists()) {
            fileToOpen += args[1];

            if (app.sendMessage(UBSettings::appPingMessage, 20000)) {
                app.sendMessage(fileToOpen, 1000000);
                return 0;
            }
        }
    }

    app.initialize(false);

    QObject::connect(&app, SIGNAL(messageReceived(const QString&)), &app, SLOT(handleOpenMessage(const QString&)));

    qDebug() << "file name argument" << fileToOpen;
    int result = app.exec(fileToOpen);

    app.cleanup();

    qDebug() << "application is quitting";



    return result;

}
Exemplo n.º 21
0
static void *
runThread(void *arg)
{
    THREAD_STRUCT *s;
    CONDITION cond;
    CTNBOOLEAN abortFlag;
    int runMode;

    s = (THREAD_STRUCT *) arg;

    cond = DUL_AcknowledgeAssociationRQ(&s->association, s->service);
    if (cond != DUL_NORMAL) {
	COND_DumpConditions();
	//goto exitLabel;
    }
    if (s->verboseDUL)
	DUL_DumpParams(s->service);

    MString logDir(s->logDir);
    MString storageDir(s->storageDir);
    MString gpppsStorageDir = storageDir + "/gppps";

    MDBPostProcMgr ppmgr(s->dbName);
    MDICOMReactor reactor;
    MSOPHandler echoHandler;
    MLQuery queryHandler(ppmgr, logDir);
    MLGPSPS gPSPSHandler(ppmgr, logDir);
    MLGPPPS gPPPSHandler(ppmgr, logDir, gpppsStorageDir);

    reactor.registerHandler(&echoHandler, DICOM_SOPCLASSVERIFICATION);
    reactor.registerHandler(&queryHandler, DICOM_SOPGPWORKLIST_FIND);
    reactor.registerHandler(&gPSPSHandler, DICOM_SOPGPSPS);
    reactor.registerHandler(&gPPPSHandler, DICOM_SOPGPPPS);

    reactor.processRequests(&s->association, s->service);

exitLabel:
    abortFlag = s->abortFlag;
    runMode = s->runMode;
    DUL_ClearServiceParameters(s->service);
    free(s->service);
    free(s);
    if (runMode == MODE_FORK) {
	exit(0);
    } else if (runMode == MODE_THREAD) {
#ifdef CTN_USE_THREADS
	THR_ObtainMutex(FAC_ATH);
	completedThreads++;
	THR_ReleaseMutex(FAC_ATH);

#ifdef _MSC_VER
	_endthread();
#else
	pthread_exit(NULL);
#endif
#endif
    } else {
	return 0;
    }
    return 0;
}