diff --git a/Core/Code/Testing/mitkImageWriterTest.cpp b/Core/Code/Testing/mitkImageWriterTest.cpp index 859160a7b3..6faa40cf0f 100644 --- a/Core/Code/Testing/mitkImageWriterTest.cpp +++ b/Core/Code/Testing/mitkImageWriterTest.cpp @@ -1,200 +1,202 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkImageWriter.h" #include "mitkDataNodeFactory.h" #include "mitkTestingMacros.h" #include #include #ifdef WIN32 #include "process.h" +#else +#include #endif std::string AppendExtension(const std::string &filename, const char *extension) { std::string new_filename = filename; new_filename += extension; return new_filename; } /** * test for "ImageWriter". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkImageWriterTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("ImageWriter") // let's create an object of our class mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myImageWriter.IsNotNull(),"Testing instantiation") // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! // load image MITK_TEST_CONDITION_REQUIRED(argc != 0, "File to load has been specified"); mitk::Image::Pointer image = NULL; mitk::DataNodeFactory::Pointer factory = mitk::DataNodeFactory::New(); try { MITK_TEST_OUTPUT(<< "Loading file: " << argv[1]); factory->SetFileName( argv[1] ); factory->Update(); MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file loaded"); mitk::DataNode::Pointer node = factory->GetOutput( 0 ); image = dynamic_cast(node->GetData()); if(image.IsNull()) { std::cout<<"file "<< argv[1]<< "is not an image - test will not be applied."<SetInput(image); MITK_TEST_CONDITION_REQUIRED(myImageWriter->GetInput()==image,"test Set/GetInput()"); myImageWriter->SetFileName(filename); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFileName(),filename.c_str()),"test Set/GetFileName()"); myImageWriter->SetFilePrefix("pref"); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFilePrefix(),"pref"),"test Set/GetFilePrefix()"); myImageWriter->SetFilePattern("pattern"); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFilePattern(),"pattern"),"test Set/GetFilePattern()"); // write ITK .mhd image (2D and 3D only) if( image->GetDimension() <= 3 ) { try { myImageWriter->SetExtension(".mhd"); myImageWriter->Update(); std::fstream fin, fin2; fin.open(AppendExtension(filename, ".mhd").c_str(),std::ios::in); std::string rawExtension = ".raw"; fin2.open(AppendExtension(filename, ".raw").c_str(),std::ios::in); if( !fin2.is_open() ) { rawExtension = ".zraw"; fin2.open(AppendExtension(filename, ".zraw").c_str(),std::ios::in); } MITK_TEST_CONDITION_REQUIRED(fin.is_open(),"Write .mhd file"); MITK_TEST_CONDITION_REQUIRED(fin2.is_open(),"Write .raw file"); fin.close(); fin2.close(); remove(AppendExtension(filename, ".mhd").c_str()); remove(AppendExtension(filename, rawExtension.c_str()).c_str()); } catch (...) { MITK_TEST_FAILED_MSG(<< "Exception during .mhd file writing"); } } //testing more component image writing as nrrd files try { myImageWriter->SetExtension(".nrrd"); myImageWriter->Update(); std::fstream fin; fin.open(AppendExtension(filename, ".nrrd").c_str(),std::ios::in); MITK_TEST_CONDITION_REQUIRED(fin.is_open(),"Write .nrrd file"); fin.close(); remove(AppendExtension(filename, ".nrrd").c_str()); } catch(...) { MITK_TEST_FAILED_MSG(<< "Exception during .nrrd file writing"); } // testing image writing as png files // test only for 2D images since the PNG is using a series writer in case a 3D image // should be saved -> the output name comparison would fail and also the use case // is very uncommon // write ITK .mhd image (2D and 3D only) if( image->GetDimension() == 2 ) { try { myImageWriter->SetExtension(".png"); myImageWriter->Update(); std::fstream fin; fin.open(AppendExtension(filename, ".png").c_str(),std::ios::in); MITK_TEST_CONDITION_REQUIRED(fin.is_open(),"Write .png file"); fin.close(); remove(AppendExtension(filename, ".png").c_str()); } catch(itk::ExceptionObject &e) { MITK_TEST_FAILED_MSG(<< "Exception during .png file writing: " << e.what() ); } } // test for exception handling try { MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject) myImageWriter->SetInput(image); myImageWriter->SetFileName("/usr/bin"); myImageWriter->Update(); MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject) } catch(...) { //this means that a wrong exception (i.e. no itk:Exception) has been thrown MITK_TEST_FAILED_MSG(<< "Wrong exception (i.e. no itk:Exception) caught during write"); } // always end with this! MITK_TEST_END(); } diff --git a/Modules/IGT/Testing/mitkTimeStampTest.cpp b/Modules/IGT/Testing/mitkTimeStampTest.cpp index 64f3e5da2a..192f702968 100644 --- a/Modules/IGT/Testing/mitkTimeStampTest.cpp +++ b/Modules/IGT/Testing/mitkTimeStampTest.cpp @@ -1,113 +1,117 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTimeStamp.h" #include "mitkRealTimeClock.h" #include "mitkTestingMacros.h" #include "itkObject.h" //#include +#ifndef WIN32 +#include +#endif + /** * test for the class "mitkTimeStamp" */ int mitkTimeStampTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("TimeStamp") //create testing objects itk::Object::Pointer tester = itk::Object::New(); itk::Object::Pointer tester2 = itk::Object::New(); //try methods without calling CreateInstance() before (error test cases) MITK_TEST_OUTPUT(<<"Testing behavior of methodes if they are called at the wrong moment (error should occure)."); mitk::TimeStamp::GetInstance()->Start(tester2); mitk::TimeStamp::GetInstance()->Stop(tester2); //create instance of singleton time stamp class MITK_TEST_CONDITION_REQUIRED(mitk::TimeStamp::CreateInstance() != (0), "Testing GetInstance() of Singleton" ); double timestampX = mitk::TimeStamp::GetInstance()->GetElapsed(); MITK_TEST_CONDITION_REQUIRED(timestampX==-1,"..Testing method GetCurrentTimeStamp()."); double offsetX = mitk::TimeStamp::GetInstance()->GetOffset(tester2); MITK_TEST_CONDITION_REQUIRED(offsetX==-1.0,"..Testing method GetOffset()."); //start-tracking sets the reference-time, timestamps are relative to this time mitk::TimeStamp::GetInstance()->Start(tester); MITK_INFO << "first device has started tracking\n"; //sleeps for 20 ms #if defined (WIN32) || defined (_WIN32) Sleep(20); #else usleep(20000); #endif MITK_INFO << "supposed to have waited 20ms \n"; double time_elapsed, relative_time_elapsed; //gets time elapsed since start time_elapsed = mitk::TimeStamp::GetInstance()->GetElapsed(); MITK_INFO << "have actually waited : " << time_elapsed << "ms \n"; //elapsed time is not allowed to be too far from 20 ms (+-10ms)-> debugging "destroys" the correct value of course MITK_TEST_CONDITION_REQUIRED((time_elapsed-20) > -10 , "Testing if elapsed time is correct (-10)"); //MITK_TEST_CONDITION_REQUIRED((time_elapsed-20) < 10 , "Testing if elapsed time is correct (+10)"); //second "device" starts tracking mitk::TimeStamp::GetInstance()->Start(tester2); MITK_INFO << "second device has started\n"; //first device stops mitk::TimeStamp::GetInstance()->Stop(tester); MITK_INFO << "first device has stopped tracking\n"; time_elapsed = mitk::TimeStamp::GetInstance()->GetElapsed(); relative_time_elapsed = mitk::TimeStamp::GetInstance()->GetElapsed(tester2); MITK_INFO << "time elapsed supposed to be greater than 20 ms\n"; MITK_INFO << time_elapsed << " actually elapsed\n"; MITK_INFO << "relative time elapsed supposed to be smaller than absolute time elapsed : \n"; MITK_INFO << relative_time_elapsed << " actually elapsed\n"; //relative timespan must be smaller than absolute timespan MITK_TEST_CONDITION_REQUIRED( time_elapsed > relative_time_elapsed , " testing if relative timespan is shorter than absolute timespan"); //timestamp still has to be valid (tester2 still tracking), and has to be larger than 20ms //MITK_TEST_CONDITION_REQUIRED( time_elapsed > 15 , "testing if second device is still keeping the TimeStamp \"alive\""); mitk::TimeStamp::GetInstance()->Stop(tester2); MITK_INFO << " second device has stopped tracking\n"; time_elapsed = mitk::TimeStamp::GetInstance()->GetElapsed(); //when all devices have stopped, -1 has to be returned MITK_TEST_CONDITION_REQUIRED( time_elapsed == -1 , "testing if -1 is returned after all devices have stopped"); //test set realtime clock mitk::RealTimeClock::Pointer myRealTimeClock = mitk::RealTimeClock::New(); mitk::TimeStamp::GetInstance()->SetRealTimeClock(myRealTimeClock); // always end with this! MITK_TEST_END(); } diff --git a/Utilities/qtsingleapplication/qtlocalpeer.cpp b/Utilities/qtsingleapplication/qtlocalpeer.cpp index 66501cae54..a1fb92e09c 100644 --- a/Utilities/qtsingleapplication/qtlocalpeer.cpp +++ b/Utilities/qtsingleapplication/qtlocalpeer.cpp @@ -1,197 +1,198 @@ /**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ****************************************************************************/ #include "qtlocalpeer.h" #include #include #if defined(Q_OS_WIN) #include #include typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); static PProcessIdToSessionId pProcessIdToSessionId = 0; #endif #if defined(Q_OS_UNIX) #include +#include #endif namespace QtLP_Private { #include "qtlockedfile.cpp" #if defined(Q_OS_WIN) #include "qtlockedfile_win.cpp" #else #include "qtlockedfile_unix.cpp" #endif } const char* QtLocalPeer::ack = "ack"; QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) : QObject(parent), id(appId) { QString prefix = id; if (id.isEmpty()) { id = QCoreApplication::applicationFilePath(); #if defined(Q_OS_WIN) id = id.toLower(); #endif prefix = id.section(QLatin1Char('/'), -1); } prefix.remove(QRegExp("[^a-zA-Z]")); prefix.truncate(6); QByteArray idc = id.toUtf8(); quint16 idNum = qChecksum(idc.constData(), idc.size()); socketName = QLatin1String("qtsingleapp-") + prefix + QLatin1Char('-') + QString::number(idNum, 16); #if defined(Q_OS_WIN) if (!pProcessIdToSessionId) { QLibrary lib("kernel32"); pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); } if (pProcessIdToSessionId) { DWORD sessionId = 0; pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); socketName += QLatin1Char('-') + QString::number(sessionId, 16); } #else - socketName += QLatin1Char('-') + QString::number(::getuid(), 16); + socketName += QLatin1Char('-') + QString::number(getuid(), 16); #endif server = new QLocalServer(this); QString lockName = QDir(QDir::tempPath()).absolutePath() + QLatin1Char('/') + socketName + QLatin1String("-lockfile"); lockFile.setFileName(lockName); lockFile.open(QIODevice::ReadWrite); } bool QtLocalPeer::isClient() { if (lockFile.isLocked()) return false; if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) return true; bool res = server->listen(socketName); #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) // ### Workaround if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); res = server->listen(socketName); } #endif if (!res) qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection())); return false; } bool QtLocalPeer::sendMessage(const QByteArray &message, int timeout) { if (!isClient()) return false; QLocalSocket socket; bool connOk = false; for(int i = 0; i < 2; i++) { // Try twice, in case the other instance is just starting up socket.connectToServer(socketName); connOk = socket.waitForConnected(timeout/2); if (connOk || i) break; int ms = 250; #if defined(Q_OS_WIN) Sleep(DWORD(ms)); #else struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; nanosleep(&ts, NULL); #endif } if (!connOk) return false; QDataStream ds(&socket); ds.writeBytes(message.constData(), message.size()); bool res = socket.waitForBytesWritten(timeout); if (res) { res &= socket.waitForReadyRead(timeout); // wait for ack if (res) res &= (socket.read(qstrlen(ack)) == ack); } return res; } void QtLocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); if (!socket) return; while (socket->bytesAvailable() < (int)sizeof(quint32)) socket->waitForReadyRead(); QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); if (got < 0) { qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; } socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); delete socket; emit messageReceived(uMsg); //### (might take a long time to return) }