Example #1
0
void QtDownload::downloadFinished(QNetworkReply *data)
{
    QString addr="/home/anomaly/"+file;
    QFile localFile(file);
    if (!localFile.open(QIODevice::WriteOnly))
     {
        qDebug()<<"cant access";
        return;
    }
    sdata = data->readAll();
    localFile.write(sdata);
    localFile.close();

    emit done();
}
Example #2
0
    Dialog()
    {
        QString localFile("test.html");
        // server/shared/test.html should be replaced to point to a real file
        QString UNCPath("file://server/shared/test.html");

        QVBoxLayout* vBox = new QVBoxLayout();
        vBox->addWidget(new QLabel("Clicking on the links should open their"
                                   " contents in the default browser !"));
        vBox->addWidget(createLink(localFile));
        vBox->addWidget(new QLabel("The following link must point to "
                                   "a file in a shared folder on a network !"));
        vBox->addWidget(createLink(UNCPath));
        setLayout(vBox);
    }
void plManifestFile::DoMd5Check()
{
    if (plFileUtils::FileExists(fName.c_str()))
    {
        plMD5Checksum localFile(fName.c_str());
        fIsLocalUpToDate = (localFile == fChecksum);
        fLocalExists = true;
    }
    else
    {
        fIsLocalUpToDate = false;
        fLocalExists = false;
    }

    fMd5Checked = true;
}
Example #4
0
void QtDownload::downloadFinished(QNetworkReply *data) {
    QUrl file = this->target;
    QFileInfo fileInfo(file.path());
    QString fileName = fileInfo.fileName();
    QString home = this->saveto;
    home += "/"+fileName;
    QFile localFile(home);
    if (!localFile.open(QIODevice::WriteOnly))
        return;
    const QByteArray sdata = data->readAll();
    localFile.write(sdata);
    //qDebug() << sdata;
    localFile.close();

    emit done();
}
Example #5
0
SftpJobId SftpChannel::downloadFile(const QString &remoteFilePath,
    const QString &localFilePath, SftpOverwriteMode mode)
{
    QSharedPointer<QFile> localFile(new QFile(localFilePath));
    if (mode == SftpSkipExisting && localFile->exists())
        return SftpInvalidJob;
    QIODevice::OpenMode openMode = QIODevice::WriteOnly;
    if (mode == SftpOverwriteExisting)
        openMode |= QIODevice::Truncate;
    else if (mode == SftpAppendToExisting)
        openMode |= QIODevice::Append;
    if (!localFile->open(openMode))
        return SftpInvalidJob;
    return d->createJob(Internal::SftpDownload::Ptr(
        new Internal::SftpDownload(++d->m_nextJobId, remoteFilePath, localFile)));
}
Example #6
0
void plManifestFile::DoMd5Check()
{
    if (plFileInfo(fName).Exists())
    {
        plMD5Checksum localFile(fName);
        fIsLocalUpToDate = (localFile == fChecksum);
        fLocalExists = true;
    }
    else
    {
        fIsLocalUpToDate = false;
        fLocalExists = false;
    }

    fMd5Checked = true;
}
static std::string getLogConfig(std::string uri)
{
    std::string localPath;

    std::string::size_type fsPos = uri.find("?fs=");
    if (std::string::npos == fsPos) {
        return localPath;
    }

    std::string IOR = uri.substr(fsPos + 4);
    CORBA::Object_var obj = ossie::corba::stringToObject(IOR);
    if (CORBA::is_nil(obj)) {
        return localPath;
    }

    CF::FileSystem_var fileSystem = CF::FileSystem::_narrow(obj);
    if (CORBA::is_nil(fileSystem)) {
        return localPath;
    }

    std::string remotePath = uri.substr(0, fsPos);
    CF::OctetSequence_var data;
    try {
        CF::File_var remoteFile = fileSystem->open(remotePath.c_str(), true);
        CORBA::ULong size = remoteFile->sizeOf();
        remoteFile->read(data, size);
    } catch (...) {
        return localPath;
    }

    std::string tempPath = remotePath;
    std::string::size_type slashPos = remotePath.find_last_of('/');
    if (std::string::npos != slashPos) {
        tempPath.erase(0, slashPos + 1);
    }
    std::fstream localFile(tempPath.c_str(), std::ios::out|std::ios::trunc);
    if (!localFile) {
        return localPath;
    }

    if (localFile.write((const char*)data->get_buffer(), data->length())) {
        localPath = tempPath;
    }
    localFile.close();

    return localPath;
}
Example #8
0
    bool setText(const QString& text) override {
      Q_ASSERT(!onDiskChangesForbidden);
      QString localFile(m_document.toUrl().toLocalFile());

      QFile file( localFile );
      if ( file.open(QIODevice::WriteOnly) )
      {
          QByteArray data = text.toLocal8Bit();

          if(file.write(data) == data.size())
          {
              ModificationRevision::clearModificationCache(m_document);
              return true;
          }
      }
      return false;
    }
Example #9
0
QByteArray getFileMd5(QString filePath)
{
	QFile localFile(filePath);

	if (!localFile.open(QFile::ReadOnly))
	{
		qDebug() << "file open error.";
		return 0;
	}

	QCryptographicHash ch(QCryptographicHash::Md5);

	quint64 totalBytes = 0;
	quint64 bytesWritten = 0;
	quint64 bytesToWrite = 0;
	quint64 loadSize = 1024 * 4;
	QByteArray buf;

	totalBytes = localFile.size();
	bytesToWrite = totalBytes;

	while (1)
	{
		if (bytesToWrite > 0)
		{
			buf = localFile.read(qMin(bytesToWrite, loadSize));
			ch.addData(buf);
			bytesWritten += buf.length();
			bytesToWrite -= buf.length();
			buf.resize(0);
		}
		else
		{
			break;
		}

		if (bytesWritten == totalBytes)
		{
			break;
		}
	}

	localFile.close();
	QByteArray md5 = ch.result();
	return md5;
}
/**
 * Writes test fileset specified archive
 * @param archive archive
 */
static void writeTestFilesToArchive(KArchive *archive)
{
    QVERIFY(archive->writeFile("empty", "", 0100644, "weis", "users"));
    QVERIFY(archive->writeFile("test1", QByteArray("Hallo"), 0100440, QString("weis"), QString("users")));
    // Now let's try with the prepareWriting/writeData/finishWriting API
    QVERIFY(archive->prepareWriting("test2", "weis", "users", 8));
    QVERIFY(archive->writeData("Hallo ", 6));
    QVERIFY(archive->writeData("Du", 2));
    QVERIFY(archive->finishWriting(8));
    // Add local file
    QFile localFile(QStringLiteral("test3"));
    QVERIFY(localFile.open(QIODevice::WriteOnly));
    QVERIFY(localFile.write("Noch so einer", 13) == 13);
    localFile.close();

    QVERIFY(archive->addLocalFile("test3", "z/test3"));

    // writeFile API
    QVERIFY(archive->writeFile("my/dir/test3", "I do not speak German\nDavid.", 0100644, "dfaure", "hackers"));

    // Now a medium file : 100 null bytes
    char medium[SIZE1];
    memset(medium, 0, SIZE1);
    QVERIFY(archive->writeFile("mediumfile", QByteArray(medium, SIZE1)));
    // Another one, with an absolute path
    QVERIFY(archive->writeFile("/dir/subdir/mediumfile2", QByteArray(medium, SIZE1)));

    // Now a huge file : 20000 null bytes
    int n = 20000;
    char *huge = new char[n];
    memset(huge, 0, n);
    QVERIFY(archive->writeFile("hugefile", QByteArray(huge, n)));
    delete [] huge;

    // Now an empty directory
    QVERIFY(archive->writeDir("aaaemptydir"));

#ifndef Q_OS_WIN
    // Add local symlink
    QVERIFY(archive->addLocalFile("test3_symlink", "z/test3_symlink"));
#endif

    // Add executable
    QVERIFY(archive->writeFile("executableAll", "#!/bin/sh\necho hi", 0100755));
}
void MachinetalkService::fileToObject(const machinetalk::File &file, QObject *object, const QString &tempDir)
{
    if (!(file.has_name() && file.has_blob() && file.has_encoding())) {
        return;
    }

    const QString &fileName = QString::fromStdString(file.name());
    QString uuid = QUuid::createUuid().toString();
    uuid = uuid.replace('{', '_').replace('}', '_');
    const QString &filePath = QDir(tempDir).filePath(uuid + fileName);
    QFile localFile(filePath);

    if (!localFile.open(QIODevice::WriteOnly))
    {
        qWarning() << "not able to create file" << filePath;
        return;
    }

    const auto &data = QByteArray::fromRawData(file.blob().data(), static_cast<int>(file.blob().size()));

    if (file.encoding() == machinetalk::ZLIB)
    {
        qWarning() << "zlib encoding may not work";
        const QByteArray uncompressedData = qUncompress(data); // TODO: zlib uncompress not working correctly
        localFile.write(uncompressedData);
        localFile.close();
    }
    else if (file.encoding() == machinetalk::CLEARTEXT) {

        localFile.write(data);
        localFile.close();
    }
    else
    {
        qWarning() << "unknown file encoding";
        localFile.close();
        return;
    }

    object->setProperty("name", QVariant::fromValue(fileName));
    object->setProperty("url", QVariant::fromValue(QUrl::fromLocalFile(filePath).toString()));
}
Example #12
0
void ThumbnailPicker::slotSetFromURL() {
    //Attempt to load the specified URL
    QUrl u = ui->ImageURLBox->url();

    if ( u.isValid() ) {
        if ( u.isLocalFile() ) {
            QFile localFile( u.toLocalFile() );

            //Add image to list
            //If image is taller than desktop, rescale it.
            QImage im( localFile.fileName() );

            if ( im.isNull() ) {
                KMessageBox::sorry( 0,
                                    i18n("Failed to load image at %1", localFile.fileName() ),
                                    i18n("Failed to load image") );
                return;
            }

            uint w = im.width();
            uint h = im.height();
            uint pad = 0;/* FIXME later 4*marginHint() + 2*ui->SearchLabel->height() + actionButton( Ok )->height() + 25; */
            uint hDesk = QApplication::desktop()->availableGeometry().height() - pad;

            if ( h > hDesk )
                im = im.scaled( w*hDesk/h, hDesk, Qt::IgnoreAspectRatio, Qt::SmoothTransformation );

            //Add Image to top of list and 50x50 thumbnail image and URL to top of listbox
            PixList.insert( 0, new QPixmap( QPixmap::fromImage( im ) ) );
            ui->ImageList->insertItem( 0, new QListWidgetItem ( QIcon(shrinkImage( PixList.last(), 50 )), u.url() ));

            //Select the new image
            ui->ImageList->setCurrentRow( 0 );
            slotSetFromList(0);

        } else {
            KIO::StoredTransferJob *j = KIO::storedGet( u, KIO::NoReload, KIO::HideProgressInfo );
            j->setUiDelegate(0);
            connect( j, SIGNAL( result(KJob*) ), SLOT( slotJobResult(KJob*) ) );
        }
    }
}
void ImageVtkLegacyIO::Write()
{
  ValidateOutputLocation();

  const Image* input = dynamic_cast<const Image*>(this->GetInput());

  vtkSmartPointer<vtkStructuredPointsWriter> writer = vtkSmartPointer<vtkStructuredPointsWriter>::New();

  // The legacy vtk image writer cannot write to streams
  LocalFile localFile(this);
  writer->SetFileName(localFile.GetFileName().c_str());

  ImageVtkReadAccessor vtkReadAccessor(Image::ConstPointer(input), NULL, input->GetVtkImageData());
  writer->SetInputData(const_cast<vtkImageData*>(vtkReadAccessor.GetVtkImageData()));

  if (writer->Write() == 0 || writer->GetErrorCode() != 0 )
  {
    mitkThrow() << "vtkStructuredPointesWriter error: " << vtkErrorCode::GetStringFromErrorCode(writer->GetErrorCode());
  }
}
Example #14
0
void BlFile::replyFinished(QNetworkReply * reply) {
  
  if (reply->error() == QNetworkReply::NoError) {
      
      fprintf(stderr,"Descarga completa %s\n", m_file.toLatin1().constData());
      
      QFile localFile(m_file);
      if (!localFile.open(QIODevice::WriteOnly)) {
	  fprintf(stderr,"Error en la escritura del archivo %s\n", m_file.toLatin1().constData());
	  return;
      } // end if
      const QByteArray sdata = reply->readAll();
      localFile.write(sdata);
      localFile.close();
      fprintf(stderr, "Archivo escrito %s \n %s\n", m_file.toLatin1().constData(), sdata.data());
  } else {
      fprintf(stderr,"Error descargando %s\n", fileName().toLatin1().constData());
  }
  reply->deleteLater();
}
already_AddRefed<nsMIMEInfoBase>
nsOSHelperAppService::GetFromType(const nsCString& aMIMEType)
{
	for (int i = 0; mimeTypes[i].type; i++)
	{
		if (strcasecmp(aMIMEType.get(), mimeTypes[i].type) == 0)
		{
			nsCAutoString mimeType(mimeTypes[i].type);
			nsAutoString description = NS_ConvertASCIItoUTF16(mimeTypes[i].description);;

			nsMIMEInfoAmigaOS *mimeInfo = new nsMIMEInfoAmigaOS(mimeType);
			NS_ADDREF(mimeInfo);

			if (mimeTypes[i].handler)
			{
				nsCAutoString path(mimeTypes[i].handler);
				nsAutoString handler = NS_ConvertASCIItoUTF16(mimeTypes[i].handlerDesc);

				nsCOMPtr<nsILocalFile> localFile (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID));
				localFile->InitWithNativePath(path);

				NS_IF_ADDREF(localFile);

				mimeInfo->SetDescription(nsAutoString(description));
				mimeInfo->SetDefaultApplication(localFile);
				mimeInfo->SetDefaultDescription(handler);
				mimeInfo->SetPreferredAction(nsIMIMEInfo::useHelperApp);
			}
			else
			{
				mimeInfo->SetDescription(description);
				mimeInfo->SetPreferredAction(nsIMIMEInfo::saveToDisk);
			}

			return mimeInfo;
		}
	}

	return nsnull;
}
nsresult CheckValidHDROP(STGMEDIUM* pSTG)
{
  if (pSTG->tymed != TYMED_HGLOBAL) {
    fail("Received data is not in an HGLOBAL");
    return NS_ERROR_UNEXPECTED;
  }

  HGLOBAL hGlobal = pSTG->hGlobal;
  DROPFILES* pDropFiles;
  pDropFiles = (DROPFILES*)GlobalLock(hGlobal);
  if (!pDropFiles) {
    fail("There is no data at the given HGLOBAL");
    return NS_ERROR_UNEXPECTED;
  }

  if (pDropFiles->pFiles != sizeof(DROPFILES))
    fail("DROPFILES struct has wrong size");

  if (pDropFiles->fWide != true) {
    fail("Received data is not Unicode");
    return NS_ERROR_UNEXPECTED;
  }
  nsString s;
  unsigned long offset = 0;
  while (1) {
    s = (PRUnichar*)((char*)pDropFiles + pDropFiles->pFiles + offset);
    if (s.IsEmpty())
      break;
    nsresult rv;
    nsCOMPtr<nsIFile> localFile(
               do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
    rv = localFile->InitWithPath(s);
    if (NS_FAILED(rv)) {
      fail("File could not be opened");
      return NS_ERROR_UNEXPECTED;
    }
    offset += sizeof(PRUnichar) * (s.Length() + 1);
  }
  return NS_OK;
}
  void SurfaceVtkLegacyIO::Write()
  {
    ValidateOutputLocation();

    const Surface *input = dynamic_cast<const Surface *>(this->GetInput());

    const unsigned int timesteps = input->GetTimeGeometry()->CountTimeSteps();
    for (unsigned int t = 0; t < timesteps; ++t)
    {
      std::string fileName;
      vtkSmartPointer<vtkPolyData> polyData = this->GetPolyData(t, fileName);
      vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
      writer->SetInputData(polyData);
      if (us::any_cast<bool>(GetWriterOption("Save as binary file")))
      {
        writer->SetFileTypeToBinary();
      }
      // The legacy vtk poly data writer cannot write to streams
      LocalFile localFile(this);
      writer->SetFileName(localFile.GetFileName().c_str());

      if (writer->Write() == 0 || writer->GetErrorCode() != 0)
      {
        mitkThrow() << "Error during surface writing"
                    << (writer->GetErrorCode() ?
                          std::string(": ") + vtkErrorCode::GetStringFromErrorCode(writer->GetErrorCode()) :
                          std::string());
      }

      if (this->GetOutputStream() && input->GetTimeGeometry()->CountTimeSteps() > 1)
      {
        MITK_WARN << "Writing multiple time-steps to output streams is not supported. "
                  << "Only the first time-step will be written";
        break;
      }
    }
  }
bool QtCesterConnection::copyFileToDevice(const QString &localSource, const QString &deviceDest, bool failIfExists)
{
    debugOutput( qPrintable(QString::fromLatin1("Copy File: %1 -> %2").arg(localSource).arg(deviceDest)),0);
    QFile localFile(localSource);
    QFileInfo info(localSource);
    if (!localFile.exists() || !localFile.open(QIODevice::ReadOnly)) {
        qDebug() << "Could not open File!";
        return false;
    }

    QTcpSocket* socket = 0;
    if (!_initCommand(socket, COMMAND_CREATE_FILE)) {
        END_ERROR(socket, "Could not initialized command");
    }

    CreateFileOptions option;
    strcpy(option.fileName, qPrintable(deviceDest));
#ifdef Q_OS_WIN
    // Copy FileTime for update verification
    FILETIME creationTime, accessTime, writeTime;
    HANDLE localHandle = CreateFile(localSource.utf16(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
    if (localHandle != INVALID_HANDLE_VALUE) {
        if (GetFileTime(localHandle, &creationTime, &accessTime, &writeTime)) {
            LocalFileTimeToFileTime(&writeTime, &writeTime);
            option.fileTime = writeTime;
        }
        CloseHandle(localHandle);
    }
    DWORD attributes = GetFileAttributes(localSource.utf16());
    if (attributes != -1 )
        option.fileAttributes = attributes;
#endif
    option.fileSize = info.size();
    option.overwriteExisting = !failIfExists;

    if (!_sendData(socket, (char*) &option, sizeof(option))) {
        END_ERROR(socket, "Could not send options...");
    }

    if (!_checkResult(socket)) {
        END_ERROR(socket, "Server did not accept configuration");
    }

    int bytesWritten = 0;
    const int bufferSize = 1024;
    QByteArray data;
    while (bytesWritten < option.fileSize) {
        data = localFile.read(bufferSize);
        bytesWritten += data.size();
#ifdef Q_OS_WIN
        wprintf( L"%s -> %s (%d / %d) %d %%\r", localSource.utf16() , deviceDest.utf16(),
                 bytesWritten , option.fileSize, (100*bytesWritten)/option.fileSize );
#endif
        if (!_sendData(socket, data.constData(), data.size())) {
            END_ERROR(socket, "Error during file transfer");
        }
        if (!_checkResult(socket)) {
            END_ERROR(socket, "Got some strange result");
        }
    }
#ifdef Q_OS_WIN
    wprintf( L"\n"); // We should jump to next line...
#endif
    if (bytesWritten != option.fileSize) {
        END_ERROR(socket, "Did not send sufficient data");
    }
    _freeSocket(socket);
    return true;
}
already_AddRefed<nsMIMEInfoBase>
nsOSHelperAppService::GetFromExtension(const nsCString& aFileExt)
{
	for (int i = 0; mimeTypes[i].type; i++)
	{
		/* Try to find a match in the extensions string. */
		const char *ext = mimeTypes[i].extensions;
		const char *fileExt = aFileExt.get();
		int fileExtSize = strlen(fileExt);

		while (ext)
		{
			if (ext[0] == ' ')
				ext++;

			if (strncasecmp(fileExt, ext, fileExtSize) == 0)
			{
				/* Partial match, it's a full match if the next char is either a space or 0 */
				if (ext[fileExtSize] == 0 || ext[fileExtSize] == ' ')
					break;
			}

			ext = strchr(ext+1, ' ');
		}

		/* ext now points to the match, or is NULL. In the latter case, continue searching */
		if (!ext)
			continue;

		nsCAutoString mimeType(mimeTypes[i].type);
		nsAutoString description = NS_ConvertASCIItoUTF16(mimeTypes[i].description);

		nsMIMEInfoAmigaOS *mimeInfo = new nsMIMEInfoAmigaOS(mimeType);
		NS_ADDREF(mimeInfo);

		if (mimeTypes[i].handler)
		{
			nsCAutoString path(mimeTypes[i].handler);
			nsAutoString handler = NS_ConvertASCIItoUTF16(mimeTypes[i].handlerDesc);

			nsCOMPtr<nsILocalFile> localFile (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID));
			localFile->InitWithNativePath(path);

			NS_IF_ADDREF(localFile);

			mimeInfo->SetDescription(description);
			mimeInfo->SetDefaultApplication(localFile);
			mimeInfo->SetDefaultDescription(handler);
			mimeInfo->SetPreferredAction(nsIMIMEInfo::useHelperApp);
		}
		else
		{
			mimeInfo->SetDescription(description);
			mimeInfo->SetPreferredAction(nsIMIMEInfo::saveToDisk);
		}

		return mimeInfo;
	}

	return nsnull;
}
void MirrorServer::onReceiveDepreciated( dword client, byte message, InStream & input )
{
	log( CharString().format("Client %u sent depreciated message, message = %d", client, message ) );

	switch( message )
	{
	case SERVER_LOGIN:
		{
			dword job;
			input >> job;
			CharString id;
			input >> id;
			CharString md5;
			input >> md5;

			if ( login( client, id, md5 ) )
			{
				// log a message
				log( CharString().format("Client %u logged in as '%s'", client, (const char *)id ) );
				OutStream output( send( client, CLIENT_LOGIN ) );
				output << job << true;
			}
			else
			{
				log( CharString().format("Client %u failed to login!", client) );
				OutStream output( send( client, CLIENT_LOGIN ) );
				output << job << false;
			}
		}
		break;
	case SERVER_SEND_CRC:
		{
			dword catalogCRC = 0;

			dword job;
			input >> job;

			lock();
			CatalogIt it = m_Catalog.head();
			while( it.valid() )
			{
				catalogCRC += (*it).crc;
				it.next();
			}
			unlock();

			// the client determines if an error occured if the value is negative, clear to high bit so it doesn't think an error occured
			catalogCRC &= 0x7fffffff;		
			OutStream output( send( client, CLIENT_RECV_CRC ) );
			output << job << catalogCRC;
		}
		break;
	case SERVER_SEND_CATALOG:
		{
			lock();

			Tree< CharString, OldItem > catalog;

			CatalogIt it = m_Catalog.head();
			while( it.valid() )
			{
				OldItem item;
				item.name = (*it).name;
				item.crc = (*it).crc;
				item.size = (*it).size;

				catalog[ item.name ] = item;
				it.next();
			}

			log( CharString().format("Client %u requesting catalog", client) );
			OutStream output( send( client, CLIENT_RECV_CATALOG ) );
			output << catalog;

			unlock();
		}
		break;
	case SERVER_SEND_FILES:
		{
			Array< CharString > fileList;
			input >> fileList;

			log( CharString().format("Client %u requested %d files", client, fileList.size()) );

			dword bytesSent = 0;
			if ( canDownload( client ) )
			{
				log( CharString().format("Sending %u files to client %u", fileList.size(), client ) );

				int fileQueue = 0;
				for(int i=0;i<fileList.size();i++)
				{
					lock();
					CatalogIt find = m_Catalog.find( CharString( fileList[i] ) );
					if ( find.valid() )
					{
						OldItem item;
						item.name = (*find).name;
						item.crc = (*find).crc;
						item.size = (*find).size;

						unlock();

						// load and compress this file
						CharString localFile( m_Context.mirror + CharString(item.name) );
						if ( FileDisk::fileExists( localFile ) )
						{
							FileDisk file;
							if ( file.open( localFile, FileDisk::READ ) )
							{
								// get the latest size of the file
								item.size = file.size();
								
								OutStream output( send( client, CLIENT_RECV_FILE ) );
								output << item;

								// read the file into a buffer for sending
								byte * pBuffer = new byte[ item.size ];
								file.read( pBuffer, item.size  );

								try {
									output.write( pBuffer, item.size );
									output.flush();
								}
								catch( FileSocket::FileError )
								{}

								// release the local buffer
								delete [] pBuffer;

								fileQueue++;
								if ( fileQueue >= SEND_FILE_QUEUE )
								{
									fileQueue--;

									// wait for entire file to be received by the client
									byte fileReceived;
									input >> fileReceived;

									// stop sending if byte received is not the correct code
									if ( fileReceived != SERVER_FILE_RECEIVED )
										break;
								}

								// update the total bytes sent
								bytesSent += item.size;
							}
							else
								log( CharString().format("Failed to open local file %s!", (const char *)localFile) );
						}
						else
							log( CharString().format("Failed to find local file %s!", (const char *)localFile) );
					}
Example #21
0
  void ItkImageIO::Write()
  {
    const mitk::Image *image = dynamic_cast<const mitk::Image *>(this->GetInput());

    if (image == NULL)
    {
      mitkThrow() << "Cannot write non-image data";
    }

    // Switch the current locale to "C"
    LocaleSwitch localeSwitch("C");

    // Clone the image geometry, because we might have to change it
    // for writing purposes
    BaseGeometry::Pointer geometry = image->GetGeometry()->Clone();

    // Check if geometry information will be lost
    if (image->GetDimension() == 2 && !geometry->Is2DConvertable())
    {
      MITK_WARN << "Saving a 2D image with 3D geometry information. Geometry information will be lost! You might "
                   "consider using Convert2Dto3DImageFilter before saving.";

      // set matrix to identity
      mitk::AffineTransform3D::Pointer affTrans = mitk::AffineTransform3D::New();
      affTrans->SetIdentity();
      mitk::Vector3D spacing = geometry->GetSpacing();
      mitk::Point3D origin = geometry->GetOrigin();
      geometry->SetIndexToWorldTransform(affTrans);
      geometry->SetSpacing(spacing);
      geometry->SetOrigin(origin);
    }

    LocalFile localFile(this);
    const std::string path = localFile.GetFileName();

    MITK_INFO << "Writing image: " << path << std::endl;

    try
    {
      // Implementation of writer using itkImageIO directly. This skips the use
      // of templated itkImageFileWriter, which saves the multiplexing on MITK side.

      const unsigned int dimension = image->GetDimension();
      const unsigned int *const dimensions = image->GetDimensions();
      const mitk::PixelType pixelType = image->GetPixelType();
      const mitk::Vector3D mitkSpacing = geometry->GetSpacing();
      const mitk::Point3D mitkOrigin = geometry->GetOrigin();

      // Due to templating in itk, we are forced to save a 4D spacing and 4D Origin,
      // though they are not supported in MITK
      itk::Vector<double, 4u> spacing4D;
      spacing4D[0] = mitkSpacing[0];
      spacing4D[1] = mitkSpacing[1];
      spacing4D[2] = mitkSpacing[2];
      spacing4D[3] = 1; // There is no support for a 4D spacing. However, we should have a valid value here

      itk::Vector<double, 4u> origin4D;
      origin4D[0] = mitkOrigin[0];
      origin4D[1] = mitkOrigin[1];
      origin4D[2] = mitkOrigin[2];
      origin4D[3] = 0; // There is no support for a 4D origin. However, we should have a valid value here

      // Set the necessary information for imageIO
      m_ImageIO->SetNumberOfDimensions(dimension);
      m_ImageIO->SetPixelType(pixelType.GetPixelType());
      m_ImageIO->SetComponentType(pixelType.GetComponentType() < PixelComponentUserType ?
                                    static_cast<itk::ImageIOBase::IOComponentType>(pixelType.GetComponentType()) :
                                    itk::ImageIOBase::UNKNOWNCOMPONENTTYPE);
      m_ImageIO->SetNumberOfComponents(pixelType.GetNumberOfComponents());

      itk::ImageIORegion ioRegion(dimension);

      for (unsigned int i = 0; i < dimension; i++)
      {
        m_ImageIO->SetDimensions(i, dimensions[i]);
        m_ImageIO->SetSpacing(i, spacing4D[i]);
        m_ImageIO->SetOrigin(i, origin4D[i]);

        mitk::Vector3D mitkDirection;
        mitkDirection.SetVnlVector(geometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(i));
        itk::Vector<double, 4u> direction4D;
        direction4D[0] = mitkDirection[0];
        direction4D[1] = mitkDirection[1];
        direction4D[2] = mitkDirection[2];

        // MITK only supports a 3x3 direction matrix. Due to templating in itk, however, we must
        // save a 4x4 matrix for 4D images. in this case, add an homogneous component to the matrix.
        if (i == 3)
        {
          direction4D[3] = 1; // homogenous component
        }
        else
        {
          direction4D[3] = 0;
        }
        vnl_vector<double> axisDirection(dimension);
        for (unsigned int j = 0; j < dimension; j++)
        {
          axisDirection[j] = direction4D[j] / spacing4D[i];
        }
        m_ImageIO->SetDirection(i, axisDirection);

        ioRegion.SetSize(i, image->GetLargestPossibleRegion().GetSize(i));
        ioRegion.SetIndex(i, image->GetLargestPossibleRegion().GetIndex(i));
      }

      // use compression if available
      m_ImageIO->UseCompressionOn();

      m_ImageIO->SetIORegion(ioRegion);
      m_ImageIO->SetFileName(path);

      // Handle time geometry
      const ArbitraryTimeGeometry *arbitraryTG = dynamic_cast<const ArbitraryTimeGeometry *>(image->GetTimeGeometry());
      if (arbitraryTG)
      {
        itk::EncapsulateMetaData<std::string>(m_ImageIO->GetMetaDataDictionary(),
                                              PROPERTY_KEY_TIMEGEOMETRY_TYPE,
                                              ArbitraryTimeGeometry::GetStaticNameOfClass());

        std::stringstream stream;
        stream << arbitraryTG->GetTimeBounds(0)[0];
        for (TimeStepType pos = 0; pos < arbitraryTG->CountTimeSteps(); ++pos)
        {
          stream << " " << arbitraryTG->GetTimeBounds(pos)[1];
        }
        std::string data = stream.str();

        itk::EncapsulateMetaData<std::string>(
          m_ImageIO->GetMetaDataDictionary(), PROPERTY_KEY_TIMEGEOMETRY_TIMEPOINTS, data);
      }

      // Handle properties
      mitk::PropertyList::Pointer imagePropertyList = image->GetPropertyList();

      for (const auto &property : *imagePropertyList->GetMap())
      {
        IPropertyPersistence::InfoResultType infoList =
          mitk::CoreServices::GetPropertyPersistence()->GetInfo(property.first, GetMimeType()->GetName(), true);

        if (infoList.empty())
        {
          continue;
        }

        std::string value = infoList.front()->GetSerializationFunction()(property.second);

        if (value == mitk::BaseProperty::VALUE_CANNOT_BE_CONVERTED_TO_STRING)
        {
          continue;
        }

        std::string key = infoList.front()->GetKey();

        itk::EncapsulateMetaData<std::string>(m_ImageIO->GetMetaDataDictionary(), key, value);
      }

      ImageReadAccessor imageAccess(image);
      m_ImageIO->Write(imageAccess.GetData());
    }
    catch (const std::exception &e)
    {
      mitkThrow() << e.what();
    }
  }
Example #22
0
void QApplicationConfig::configMessageReceived(QList<QByteArray> messageList)
{
    m_rx.ParseFromArray(messageList.at(0).data(), messageList.at(0).size());

#ifdef QT_DEBUG
    std::string s;
    gpb::TextFormat::PrintToString(m_rx, &s);
    qDebug() << "server message" << QString::fromStdString(s);
#endif

    if (m_rx.type() == pb::MT_DESCRIBE_APPLICATION) // receive all provided applications
    {
        for (int i = 0; i < m_rx.app_size(); ++i)
        {
            pb::Application app;

            app = m_rx.app(i);

            QApplicationConfigItem::ApplicationType type;
            QString name;
            QString description;

            type = (QApplicationConfigItem::ApplicationType)app.type();
            name = QString::fromStdString(app.name());
            description = QString::fromStdString(app.description());

            if ((m_filter->type() == type)
                 && (m_filter->name().isEmpty() || (name == m_filter->name()))
                 && (m_filter->description().isEmpty() || description.contains(m_filter->description())))
            {
                QApplicationConfigItem *appConfigItem;

                appConfigItem = new QApplicationConfigItem(this);
                appConfigItem->setName(name);
                appConfigItem->setDescription(description);
                appConfigItem->setType(type);
                m_configs.append(appConfigItem);
                emit configsChanged(QQmlListProperty<QApplicationConfigItem>(this, m_configs));
            }
        }

        updateState(Connected); // now we are connected
    }
    else if (m_rx.type() == pb::MT_APPLICATION_DETAIL) // receive the details of an application
    {
        for (int i = 0; i < m_rx.app_size(); ++i)
        {
            pb::Application app;

            app = m_rx.app(i);

            QApplicationConfigItem::ApplicationType type;

            type = (QApplicationConfigItem::ApplicationType)app.type();

            if (m_filter->type() == type)     // detail comes when application was already filtered, so we only check the type to make sure it is compatible
            {
                QString baseFilePath;
                QStringList fileList;
                QDir dir;

                if (m_selectedConfig == NULL)
                {
                    return;
                }

                m_selectedConfig->setName(QString::fromStdString(app.name()));
                m_selectedConfig->setDescription(QString::fromStdString(app.description()));
                m_selectedConfig->setType(type);

                baseFilePath = Service::applicationTempPath(m_selectedConfig->name());
                if (!dir.mkpath(baseFilePath))
                {
                    qDebug() << "not able to create directory";
                }

#ifdef QT_DEBUG
                qDebug() << "base file path:" << baseFilePath;
#endif

                for (int j = 0; j < app.file_size(); ++j)
                {
                    pb::File file;
                    QString filePath;
                    QByteArray data;

                    file = app.file(j);
                    filePath = baseFilePath + QString::fromStdString(file.name());

                    QFileInfo fileInfo(filePath);
                    if (!dir.mkpath(fileInfo.absolutePath()))
                    {
                        qDebug() << "not able to create directory";
                    }

                    QFile localFile(filePath);
                    if (!localFile.open(QIODevice::WriteOnly))
                    {
                        qDebug() << "not able to create file" << filePath;
                        continue;
                    }

                    data = QByteArray(file.blob().data(), file.blob().size());

                    if (file.encoding() == pb::ZLIB)
                    {
                        quint32 test = ((quint32)data.at(0) << 24) + ((quint32)data.at(1) << 16) + ((quint32)data.at(2) << 8) + ((quint32)data.at(3) << 0);
                        qDebug() << test << (quint8)data.at(0) << (quint8)data.at(1) << (quint8)data.at(2) << (quint8)data.at(3);   // TODO
                        data = qUncompress(data);
                    }
                    else if (file.encoding() != pb::CLEARTEXT)
                    {
                        qDebug() << "unknown encoding";
                        localFile.close();
                        continue;
                    }

                    localFile.write(data);
                    localFile.close();

                    fileList.append(filePath);

#ifdef QT_DEBUG
                    qDebug() << "created file: " << filePath;
#endif
                }

                QApplicationDescription applicationDescription;

                applicationDescription.setSourceDir(QUrl("file:///" + baseFilePath));
                // TODO check validity

                m_selectedConfig->setFiles(fileList);
                m_selectedConfig->setMainFile(applicationDescription.mainFile());
                m_selectedConfig->setLoaded(true);
                m_selectedConfig->setLoading(false);
            }
        }
    }
}
Example #23
0
void SftpChannelPrivate::handleMkdirStatus(const JobMap::Iterator &it,
    const SftpStatusResponse &response)
{
    SftpMakeDir::Ptr op = it.value().staticCast<SftpMakeDir>();
    if (op->parentJob == SftpUploadDir::Ptr()) {
        handleStatusGeneric(it, response);
        return;
    }
    if (op->parentJob->hasError) {
        m_jobs.erase(it);
        return;
    }

    typedef QMap<SftpMakeDir::Ptr, SftpUploadDir::Dir>::Iterator DirIt;
    DirIt dirIt = op->parentJob->mkdirsInProgress.find(op);
    Q_ASSERT(dirIt != op->parentJob->mkdirsInProgress.end());
    const QString &remoteDir = dirIt.value().remoteDir;
    if (response.status == SSH_FX_OK) {
        emit dataAvailable(op->parentJob->jobId,
            tr("Created remote directory '%1'.").arg(remoteDir));
    } else if (response.status == SSH_FX_FAILURE) {
        emit dataAvailable(op->parentJob->jobId,
            tr("Remote directory '%1' already exists.").arg(remoteDir));
    } else {
        op->parentJob->setError();
        emit finished(op->parentJob->jobId,
            tr("Error creating directory '%1': %2")
            .arg(remoteDir, response.errorString));
        m_jobs.erase(it);
        return;
    }

    QDir localDir(dirIt.value().localDir);
    const QFileInfoList &dirInfos
        = localDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    foreach (const QFileInfo &dirInfo, dirInfos) {
        const QString remoteSubDir = remoteDir + QLatin1Char('/') + dirInfo.fileName();
        const SftpMakeDir::Ptr mkdirOp(
            new SftpMakeDir(++m_nextJobId, remoteSubDir, op->parentJob));
        op->parentJob->mkdirsInProgress.insert(mkdirOp,
            SftpUploadDir::Dir(dirInfo.absoluteFilePath(), remoteSubDir));
        createJob(mkdirOp);
    }

    const QFileInfoList &fileInfos = localDir.entryInfoList(QDir::Files);
    foreach (const QFileInfo &fileInfo, fileInfos) {
        QSharedPointer<QFile> localFile(new QFile(fileInfo.absoluteFilePath()));
        if (!localFile->open(QIODevice::ReadOnly)) {
            op->parentJob->setError();
            emit finished(op->parentJob->jobId,
                tr("Could not open local file '%1': %2")
                .arg(fileInfo.absoluteFilePath(), localFile->errorString()));
            m_jobs.erase(it);
            return;
        }

        const QString remoteFilePath = remoteDir + QLatin1Char('/') + fileInfo.fileName();
        SftpUploadFile::Ptr uploadFileOp(new SftpUploadFile(++m_nextJobId,
            remoteFilePath, localFile, SftpOverwriteExisting, op->parentJob));
        createJob(uploadFileOp);
        op->parentJob->uploadsInProgress.append(uploadFileOp);
    }
  void DICOMSegmentationIO::Write()
  {
    ValidateOutputLocation();

    mitk::LocaleSwitch localeSwitch("C");
    LocalFile localFile(this);
    const std::string path = localFile.GetFileName();

    auto input = dynamic_cast<const LabelSetImage *>(this->GetInput());
    if (input == nullptr)
      mitkThrow() << "Cannot write non-image data";

    // Get DICOM information from referenced image
    vector<DcmDataset *> dcmDatasets;
    DcmFileFormat *readFileFormat = new DcmFileFormat();
    try
    {
      // TODO: Generate dcmdataset witk DICOM tags from property list; ATM the source are the filepaths from the
      // property list
      mitk::StringLookupTableProperty::Pointer filesProp =
        dynamic_cast<mitk::StringLookupTableProperty *>(input->GetProperty("files").GetPointer());

      if (filesProp.IsNull())
      {
        mitkThrow() << "No property with dicom file path.";
        return;
      }

      StringLookupTable filesLut = filesProp->GetValue();
      const StringLookupTable::LookupTableType &lookUpTableMap = filesLut.GetLookupTable();

      for (auto it : lookUpTableMap)
      {
        const char *fileName = (it.second).c_str();
        if (readFileFormat->loadFile(fileName, EXS_Unknown).good())
          dcmDatasets.push_back(readFileFormat->getAndRemoveDataset());
      }
    }
    catch (const std::exception &e)
    {
      MITK_ERROR << "An error occurred while getting the dicom informations: " << e.what() << endl;
      return;
    }

    // Iterate over all layers. For each a dcm file will be generated
    for (unsigned int layer = 0; layer < input->GetNumberOfLayers(); ++layer)
    {
      vector<itkInternalImageType::Pointer> segmentations;

      try
      {
        // Cast mitk layer image to itk
        ImageToItk<itkInputImageType>::Pointer imageToItkFilter = ImageToItk<itkInputImageType>::New();
        // BUG: It must be the layer image, but there are some errors with it (dcmqi: generate the dcmSeg "No frame data
        // available") --> input->GetLayerImage(layer)
        imageToItkFilter->SetInput(input);
        imageToItkFilter->Update();

        // Cast from original itk type to dcmqi input itk image type
        typedef itk::CastImageFilter<itkInputImageType, itkInternalImageType> castItkImageFilterType;
        castItkImageFilterType::Pointer castFilter = castItkImageFilterType::New();
        castFilter->SetInput(imageToItkFilter->GetOutput());
        castFilter->Update();

        itkInternalImageType::Pointer itkLabelImage = castFilter->GetOutput();
        itkLabelImage->DisconnectPipeline();

        // Iterate over all labels. For each a segmentation image will be created
        const LabelSet *labelSet = input->GetLabelSet(layer);
        for (auto itLabel = labelSet->IteratorConstBegin(); itLabel != labelSet->IteratorConstEnd(); ++itLabel)
        {
          // Thresold over the image with the given label value
          itk::ThresholdImageFilter<itkInternalImageType>::Pointer thresholdFilter =
            itk::ThresholdImageFilter<itkInternalImageType>::New();
          thresholdFilter->SetInput(itkLabelImage);
          thresholdFilter->ThresholdOutside(itLabel->first, itLabel->first);
          thresholdFilter->SetOutsideValue(0);
          thresholdFilter->Update();
          itkInternalImageType::Pointer segmentImage = thresholdFilter->GetOutput();
          segmentImage->DisconnectPipeline();

          segmentations.push_back(segmentImage);
        }
      }
      catch (const itk::ExceptionObject &e)
      {
        MITK_ERROR << e.GetDescription() << endl;
        return;
      }

      // Create segmentation meta information
      const std::string &tmpMetaInfoFile = this->CreateMetaDataJsonFile(layer);

      MITK_INFO << "Writing image: " << path << std::endl;
      try
      {
        // Convert itk segmentation images to dicom image
        dcmqi::ImageSEGConverter *converter = new dcmqi::ImageSEGConverter();
        DcmDataset *result = converter->itkimage2dcmSegmentation(dcmDatasets, segmentations, tmpMetaInfoFile);

        // Write dicom file
        DcmFileFormat dcmFileFormat(result);

        std::string filePath = path.substr(0, path.find_last_of("."));
        // If there is more than one layer, we have to write more than 1 dicom file
        if (input->GetNumberOfLayers() != 1)
          filePath = filePath + std::to_string(layer) + ".dcm";
        else
          filePath = filePath + ".dcm";

        dcmFileFormat.saveFile(filePath.c_str(), EXS_LittleEndianExplicit);

        // Clean up
        if (converter != nullptr)
          delete converter;
        if (result != nullptr)
          delete result;
      }
      catch (const std::exception &e)
      {
        MITK_ERROR << "An error occurred during writing the DICOM Seg: " << e.what() << endl;
        return;
      }
    } // Write a dcm file for the next layer

    // End of image writing; clean up
    if (readFileFormat)
      delete readFileFormat;

    for (auto obj : dcmDatasets)
      delete obj;
    dcmDatasets.clear();
  }
Example #25
0
	void WebSocketQt::setupSocketWithSSLDataSource(SSLDataSource * dataSource)
	{
		QSslConfiguration config;

		QFile localFile(WebSocketQt::toString(dataSource->clientLocalCertificateFilePath()));
		if (localFile.open(QIODevice::ReadOnly))
		{
			QSslCertificate cert(localFile.readAll());
			localFile.close();
			if (cert.isNull())
			{
#ifdef FAYECPP_DEBUG_MESSAGES
				qDebug() << "SocketQT: LocalCertificate is NULL";
#endif
			}
			else
			{
				config.setLocalCertificate(cert);
			}
		}

		QFile keyFile(WebSocketQt::toString(dataSource->clientPrivateKeyFilePath()));
		if (keyFile.open(QIODevice::ReadOnly))
		{
			QByteArray pp;
			pp.append(WebSocketQt::toString(dataSource->clientPrivateKeyPassPhrase()));
			QSslKey key(keyFile.readAll(),
						QSsl::Rsa,
						QSsl::Pem,
						QSsl::PrivateKey,
						pp);
			pp.clear();
			keyFile.close();
			if (key.isNull())
			{
#ifdef FAYECPP_DEBUG_MESSAGES
				qDebug() << "SocketQT: PrivateKey is NULL";
#endif
			}
			else
			{
				config.setPrivateKey(key);
			}
		}

		QFile caFile(WebSocketQt::toString(dataSource->clientCACertificateFilePath()));
		if (caFile.open(QIODevice::ReadOnly))
		{
			QSslCertificate cert(caFile.readAll());
			caFile.close();
			if (cert.isNull())
			{
#ifdef FAYECPP_DEBUG_MESSAGES
				qDebug() << "SocketQT: CACertificate is NULL";
#endif
			}
			else
			{
				QList<QSslCertificate> caList(config.caCertificates());
				caList.append(cert);
				config.setCaCertificates(caList);
			}
		}

		_socket->setSslConfiguration(config);
	}
Example #26
0
BOOL CUpdateThread::Download( LPCTSTR lpszUrl, LPCTSTR lpszSavePath, ULONG uSize)
{
	DWORD dwServiceType;
	CString strServer;
	CString strObject;
	INTERNET_PORT nPort;
	BOOL bResult = FALSE;
	if (AfxParseURL(lpszUrl, dwServiceType, strServer, strObject, nPort))
	{
		CHttpConnection *conn = NULL;
		CHttpFile *file = NULL;
		UpdateSubProgress(0);
		try
		{
			int flags = INTERNET_FLAG_EXISTING_CONNECT;
			if (dwServiceType == AFX_INET_SERVICE_HTTPS) 
			{
				flags |= INTERNET_FLAG_SECURE | 
					INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
					INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
			}
			conn = m_Session.GetHttpConnection(strServer, nPort);
			file = conn->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, flags);
			file->SendRequest();
			UpdateSubProgress(10);
			DWORD dwStatus = 0;
			file->QueryInfoStatusCode(dwStatus);
			if (dwStatus == 200)
			{
				CFile localFile(lpszSavePath, CFile::modeReadWrite | CFile::shareExclusive | CFile::modeCreate);
				char buf[512];
				UINT nCount = 0;
				ULONG uTotal = 0;
				while ((nCount = file->Read(buf, 1)) > 0)
				{
					localFile.Write(buf, nCount);
					uTotal += nCount;
					if (uSize > 0)
						UpdateSubProgress(10 + 90.0 * uTotal / uSize);
				}
				localFile.Close();
				bResult = TRUE;
			}
		}
		catch (CException *e)
		{
			e->ReportError();
			e->Delete();
		}
		if (file)
		{
			file->Close();
			delete file;
		}
		if (conn)
		{
			conn->Close();
			delete conn;
		}
		UpdateSubProgress(100);
	};
	return bResult;
}
Example #27
0
void LabelSetImageIO::Write()
{
  ValidateOutputLocation();

  const LabelSetImage* input = static_cast<const LabelSetImage*>(this->GetInput());

  const std::string& locale = "C";
  const std::string& currLocale = setlocale( LC_ALL, NULL );

  if ( locale.compare(currLocale)!=0 )
  {
    try
    {
      setlocale(LC_ALL, locale.c_str());
    }
    catch(...)
    {
      mitkThrow() << "Could not set locale " << currLocale;
    }
  }

  mitk::Image::Pointer inputVector = mitk::LabelSetImageConverter::ConvertLabelSetImageToImage(input);

  // image write
  if ( inputVector.IsNull() )
  {
    mitkThrow() << "Cannot write non-image data";
  }

  itk::NrrdImageIO::Pointer nrrdImageIo = itk::NrrdImageIO::New();

  // Clone the image geometry, because we might have to change it
  // for writing purposes
  BaseGeometry::Pointer geometry = inputVector->GetGeometry()->Clone();

  // Check if geometry information will be lost
  if (inputVector->GetDimension() == 2 &&
    !geometry->Is2DConvertable())
  {
    MITK_WARN << "Saving a 2D image with 3D geometry information. Geometry information will be lost! You might consider using Convert2Dto3DImageFilter before saving.";

    // set matrix to identity
    mitk::AffineTransform3D::Pointer affTrans = mitk::AffineTransform3D::New();
    affTrans->SetIdentity();
    mitk::Vector3D spacing = geometry->GetSpacing();
    mitk::Point3D origin = geometry->GetOrigin();
    geometry->SetIndexToWorldTransform(affTrans);
    geometry->SetSpacing(spacing);
    geometry->SetOrigin(origin);
  }

  LocalFile localFile(this);
  const std::string path = localFile.GetFileName();

  MITK_INFO << "Writing image: " << path << std::endl;

  try
  {
    // Implementation of writer using itkImageIO directly. This skips the use
    // of templated itkImageFileWriter, which saves the multiplexing on MITK side.

    const unsigned int dimension = inputVector->GetDimension();
    const unsigned int* const dimensions = inputVector->GetDimensions();
    const mitk::PixelType pixelType = inputVector->GetPixelType();
    const mitk::Vector3D mitkSpacing = geometry->GetSpacing();
    const mitk::Point3D mitkOrigin = geometry->GetOrigin();

    // Due to templating in itk, we are forced to save a 4D spacing and 4D Origin,
    // though they are not supported in MITK
    itk::Vector<double, 4u> spacing4D;
    spacing4D[0] = mitkSpacing[0];
    spacing4D[1] = mitkSpacing[1];
    spacing4D[2] = mitkSpacing[2];
    spacing4D[3] = 1; // There is no support for a 4D spacing. However, we should have a valid value here

    itk::Vector<double, 4u> origin4D;
    origin4D[0] = mitkOrigin[0];
    origin4D[1] = mitkOrigin[1];
    origin4D[2] = mitkOrigin[2];
    origin4D[3] = 0; // There is no support for a 4D origin. However, we should have a valid value here

    // Set the necessary information for imageIO
    nrrdImageIo->SetNumberOfDimensions(dimension);
    nrrdImageIo->SetPixelType(pixelType.GetPixelType());
    nrrdImageIo->SetComponentType(pixelType.GetComponentType() < PixelComponentUserType ?
      static_cast<itk::ImageIOBase::IOComponentType>(pixelType.GetComponentType()) :
      itk::ImageIOBase::UNKNOWNCOMPONENTTYPE);
    nrrdImageIo->SetNumberOfComponents(pixelType.GetNumberOfComponents());

    itk::ImageIORegion ioRegion(dimension);

    for (unsigned int i = 0; i < dimension; i++)
    {
      nrrdImageIo->SetDimensions(i, dimensions[i]);
      nrrdImageIo->SetSpacing(i, spacing4D[i]);
      nrrdImageIo->SetOrigin(i, origin4D[i]);

      mitk::Vector3D mitkDirection;
      mitkDirection.SetVnlVector(geometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(i));
      itk::Vector<double, 4u> direction4D;
      direction4D[0] = mitkDirection[0];
      direction4D[1] = mitkDirection[1];
      direction4D[2] = mitkDirection[2];

      // MITK only supports a 3x3 direction matrix. Due to templating in itk, however, we must
      // save a 4x4 matrix for 4D images. in this case, add an homogneous component to the matrix.
      if (i == 3)
      {
        direction4D[3] = 1; // homogenous component
      }
      else
      {
        direction4D[3] = 0;
      }
      vnl_vector<double> axisDirection(dimension);
      for (unsigned int j = 0; j < dimension; j++)
      {
        axisDirection[j] = direction4D[j] / spacing4D[i];
      }
      nrrdImageIo->SetDirection(i, axisDirection);

      ioRegion.SetSize(i, inputVector->GetLargestPossibleRegion().GetSize(i));
      ioRegion.SetIndex(i, inputVector->GetLargestPossibleRegion().GetIndex(i));
    }

    //use compression if available
    nrrdImageIo->UseCompressionOn();

    nrrdImageIo->SetIORegion(ioRegion);
    nrrdImageIo->SetFileName(path);

    // label set specific meta data
    char keybuffer[512];
    char valbuffer[512];

    sprintf(keybuffer, "modality");
    sprintf(valbuffer, "org.mitk.image.multilabel");
    itk::EncapsulateMetaData<std::string>(nrrdImageIo->GetMetaDataDictionary(), std::string(keybuffer), std::string(valbuffer));

    sprintf(keybuffer, "layers");
    sprintf(valbuffer, "%1d", input->GetNumberOfLayers());
    itk::EncapsulateMetaData<std::string>(nrrdImageIo->GetMetaDataDictionary(), std::string(keybuffer), std::string(valbuffer));

    for (unsigned int layerIdx = 0; layerIdx<input->GetNumberOfLayers(); layerIdx++)
    {
      sprintf(keybuffer, "layer_%03d", layerIdx); // layer idx
      sprintf(valbuffer, "%1d", input->GetNumberOfLabels(layerIdx)); // number of labels for the layer
      itk::EncapsulateMetaData<std::string>(nrrdImageIo->GetMetaDataDictionary(), std::string(keybuffer), std::string(valbuffer));

      mitk::LabelSet::LabelContainerConstIteratorType iter = input->GetLabelSet(layerIdx)->IteratorConstBegin();
      unsigned int count(0);
      while (iter != input->GetLabelSet(layerIdx)->IteratorConstEnd())
      {
        std::auto_ptr<TiXmlDocument> document;
        document.reset(new TiXmlDocument());

        TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", ""); // TODO what to write here? encoding? etc....
        document->LinkEndChild(decl);
        TiXmlElement * labelElem = GetLabelAsTiXmlElement(iter->second);
        document->LinkEndChild(labelElem);
        TiXmlPrinter printer;
        printer.SetIndent("");
        printer.SetLineBreak("");

        document->Accept(&printer);

        sprintf(keybuffer, "org.mitk.label_%03u_%05u", layerIdx, count);
        itk::EncapsulateMetaData<std::string>(nrrdImageIo->GetMetaDataDictionary(), std::string(keybuffer), printer.Str());
        ++iter;
        ++count;
      }
    }
    // end label set specific meta data

    ImageReadAccessor imageAccess(inputVector);
    nrrdImageIo->Write(imageAccess.GetData());
  }
  catch (const std::exception& e)
  {
    mitkThrow() << e.what();
  }
  // end image write

  try
  {
    setlocale(LC_ALL, currLocale.c_str());
  }
  catch(...)
  {
    mitkThrow() << "Could not reset locale " << currLocale;
  }
}
Example #28
0
 MyPersistenceManager()
 {
     wxFileName localFile(wxStandardPaths::Get().GetUserDataDir(), "persistency.ini");
     m_config = new wxFileConfig("codelite-terminal", "CodeLite", localFile.GetFullPath());
 }
Example #29
0
nsresult
net_GetFileFromURLSpec(const nsACString &aURL, nsIFile **result)
{
    nsresult rv;

    nsCOMPtr<nsIFile> localFile(
            do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
    if (NS_FAILED(rv)) {
        NS_ERROR("Only nsIFile supported right now");
        return rv;
    }

    localFile->SetFollowLinks(true);

    const nsACString *specPtr;

    nsAutoCString buf;
    if (net_NormalizeFileURL(aURL, buf))
        specPtr = &buf;
    else
        specPtr = &aURL;
    
    nsAutoCString directory, fileBaseName, fileExtension;
    
    rv = net_ParseFileURL(*specPtr, directory, fileBaseName, fileExtension);
    if (NS_FAILED(rv)) return rv;

    nsAutoCString path;

    if (!directory.IsEmpty()) {
        NS_EscapeURL(directory, esc_Directory|esc_AlwaysCopy, path);
        if (path.Length() > 2 && path.CharAt(2) == '|')
            path.SetCharAt(':', 2);
        path.ReplaceChar('/', '\\');
    }    
    if (!fileBaseName.IsEmpty())
        NS_EscapeURL(fileBaseName, esc_FileBaseName|esc_AlwaysCopy, path);
    if (!fileExtension.IsEmpty()) {
        path += '.';
        NS_EscapeURL(fileExtension, esc_FileExtension|esc_AlwaysCopy, path);
    }
    
    NS_UnescapeURL(path);
    if (path.Length() != strlen(path.get()))
        return NS_ERROR_FILE_INVALID_PATH;

    // remove leading '\'
    if (path.CharAt(0) == '\\')
        path.Cut(0, 1);

    if (IsUTF8(path))
        rv = localFile->InitWithPath(NS_ConvertUTF8toUTF16(path));
        // XXX In rare cases, a valid UTF-8 string can be valid as a native 
        // encoding (e.g. 0xC5 0x83 is valid both as UTF-8 and Windows-125x).
        // However, the chance is very low that a meaningful word in a legacy
        // encoding is valid as UTF-8.
    else 
        // if path is not in UTF-8, assume it is encoded in the native charset
        rv = localFile->InitWithNativePath(path);

    if (NS_FAILED(rv)) return rv;

    NS_ADDREF(*result = localFile);
    return NS_OK;
}
Example #30
0
/**
* ReceiveFolder
*
* Description: Download a folder and all of its contents to the local store.
*
* Param: con - describes the ftp server to connect to.
*		 file - describes the folder path + (folder)name to download.
*		 waitDialog - notification recipient.
*
* Return: bool - TODO...
*/
bool CFtpManager::ReceiveFolder(CConnection * con, CFileContainer & file, CWaitDialog & waitDialog) 
{
	bool result = false;
	
	CString localStorePath;
	GetLocalStorePath(con, localStorePath); // could always use file.localPath
	
	CString localStoreFolder = localStorePath + CString(file.path + file.name) + _T("\\");
	localStoreFolder.Replace('/', '\\');

	// Check
	if(file.dir == false)
	{
		return false;
	}

	// Create local folder
	WIN32_FIND_DATA  data; 
	//HANDLE handle = FindFirstFile(localStoreFolder, &data); 
	//if ( handle == INVALID_HANDLE_VALUE )
	if( GetFileAttributes(localStoreFolder) == INVALID_FILE_ATTRIBUTES )
	{
		int i = 0;
		CreateDirectory(localStoreFolder, NULL);
	}

	CFtpManager ftp;
	std::vector<CFileContainer> files;
	bool r = ftp.ReadLocalDirectory(con, CString(file.path + file.name + _T("/")) , files);
	if(r == false) // directory information not present.
	{
		GetFtpDirectory(con, CString(file.path + file.name + _T("/")), NULL);
		ftp.ReadLocalDirectory(con, CString(file.path + file.name + _T("/")) , files);
	}

	int i = 0;
	for(i = 0; i < files.size(); i++)
	{
		CFileContainer f;
		f = (CFileContainer)files[i];

		if(f.dir)
		{

			ReceiveFolder(con, f, waitDialog);
		}
		else 
		{
			// does the file exist, and is it current?
			bool download = false;
			CString localFile(localStorePath + f.path + f.name);
			localFile.Replace('/', '\\');
			if ( 0xFFFFFFFF == GetFileAttributes ( localFile ) && GetLastError() == ERROR_FILE_NOT_FOUND )
			{
				download = true;
			}

			if(download)
			{
				ReceiveFile(con, f, waitDialog);
			}
		}
	}
	return result;
}