Esempio n. 1
0
///////////////////////////////////////////////////////////////////////////
//  <summary>
//  Processes the appropriate operation using the Operation Packet and
//  StreamData objects given during construction.
//  Overrides IMgServiceHander::ProcessOperation().
//  </summary>
IMgServiceHandler::MgProcessStatus MgServerAdminServiceHandler::ProcessOperation()
{
    IMgServiceHandler::MgProcessStatus status = IMgServiceHandler::mpsError;
    auto_ptr<IMgOperationHandler> handler;

    MG_TRY()

    handler.reset(MgServerAdminOperationFactory::GetOperation(
                      m_packet.m_OperationID, m_packet.m_OperationVersion));
    assert(NULL != handler.get());

    handler->Initialize(m_data, m_packet);
    handler->Execute();

    status = IMgServiceHandler::mpsDone;

    MG_CATCH(L"MgServerAdminServiceHandler.ProcessOperation")

    if (mgException != NULL && NULL != handler.get())
    {
        status = (handler.get()->HandleException(mgException) ?
                  IMgServiceHandler::mpsDone : IMgServiceHandler::mpsError);
    }

    if (IMgServiceHandler::mpsDone != status)
    {
        MG_THROW();
    }

    return status;
}
Esempio n. 2
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Return currently defined locale for user, or default locale.
///
STRING MgException::GetLocale() throw()
{
    STRING locale;

    MG_TRY()

    if (NULL != sm_localeCallbackFunc)
    {
        locale = (*sm_localeCallbackFunc)();
    }

    MG_CATCH_AND_RELEASE()

    if (locale.empty())
    {
        MG_TRY()

        MgConfiguration* configuration = MgConfiguration::GetInstance();

        if (NULL != configuration && configuration->IsFileLoaded())
        {
            configuration->GetStringValue(
                MgFoundationConfigProperties::GeneralPropertiesSection,
                MgFoundationConfigProperties::GeneralPropertyDefaultMessageLocale,
                locale,
                MgFoundationConfigProperties::DefaultGeneralPropertyDefaultMessageLocale);
        }

        MG_CATCH_AND_RELEASE()

        if (locale.empty())
        {
            locale = MgResources::DefaultMessageLocale;
        }
    }
Esempio n. 3
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Construct a MgException.
///
MgException::MgException(CREFSTRING methodName, INT32 lineNumber,
    CREFSTRING fileName, MgStringCollection* whatArguments,
    CREFSTRING whyMessageId, MgStringCollection* whyArguments) throw() :
    m_whyMessageId(whyMessageId)
{
    MG_TRY()

    AddStackTraceInfo(methodName, lineNumber, fileName);

    if (NULL != whatArguments)
    {
        for (INT32 i = 0; i < whatArguments->GetCount(); ++i)
        {
            m_whatArguments.Add(MgUtil::EncodeXss(whatArguments->GetItem(i)));
        }
    }

    if (NULL != whyArguments)
    {
        for (INT32 i = 0; i < whyArguments->GetCount(); ++i)
        {
            m_whyArguments.Add(MgUtil::EncodeXss(whyArguments->GetItem(i)));
        }
    }

    MG_CATCH_AND_RELEASE()
}
Esempio n. 4
0
/////////////////////////////////////////////////////////////////
/// <summary>
/// Placeholder to associate user information with a service.
/// Not implemented in the base Service class.
/// </summary>
MgUserInformation* MgService::GetUserInfo()
{
    MG_TRY()
        throw new MgNotImplementedException(L"MgService.GetUserInfo", __LINE__, __WFILE__, NULL, L"", NULL);
    MG_CATCH_AND_THROW(L"MgService.GetUserInfo");
    return NULL;
}
Esempio n. 5
0
OrientedPolyPolygon::OrientedPolyPolygon(int nExpectedBoundaries) :
    m_nBoundaries(0),
    m_maxBoundaries(0),
    m_boundaryExt(NULL),
    m_nBoundaryVerts(NULL),
    m_totalVertices(0),
    m_boundaries(NULL)
{
    assert(nExpectedBoundaries > 0);

    MG_TRY()

    m_nBoundaryVerts = new int[nExpectedBoundaries];
    m_boundaryExt = new OpsFloatExtent[nExpectedBoundaries];
    m_boundaries = new OpsFloatPoint *[nExpectedBoundaries];
    m_maxBoundaries = nExpectedBoundaries;

    MG_CATCH(L"OrientedPolyPolygon.OrientedPolyPolygon")

    if (mgException != 0) // mgException is defined in MG_TRY() macro
    {
        Cleanup();
    }

    MG_THROW()

} // end: constructor
Esempio n. 6
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Enumerate the resource documents in the specified repository.
///
STRING MgProxyResourceService::EnumerateResourceDocuments(
    MgStringCollection* resources, CREFSTRING type, INT32 properties)
{
    STRING resourceList;
    MgCommand cmd;

    MG_TRY()

    cmd.ExecuteCommand(
        m_connProp,                                         // Connection
        MgCommand::knString,                                // Return type
        MgResourceService::opIdEnumerateResourceDocuments,  // Command code
        3,                                                  // Number of arguments
        Resource_Service,                                   // Service ID
        BUILD_VERSION(1,0,0),                               // Operation version
        MgCommand::knObject, resources,                     // Argument #1
        MgCommand::knString, &type,                         // Argument #2
        MgCommand::knInt32, properties,                     // Argument #3
        MgCommand::knNone);

    SetWarning(cmd.GetWarningObject());

    resourceList = *(cmd.GetReturnValue().val.m_str);
    delete cmd.GetReturnValue().val.m_str;

    MG_CATCH_AND_THROW(L"MgProxyResourceService.EnumerateResourceDocuments")

    return resourceList;
}
Esempio n. 7
0
void c_RestResponse::SendError(MgException* e)
{
  MG_TRY()
    
  #ifdef _MG_ENT_2011
    STRING shortError = mgException->GetExceptionMessage();
  #else
    STRING shortError = mgException->GetMessage();
  #endif
  STRING longError = e->GetDetails();
  STRING statusMessage = e->GetClassName();

  //TODO: Use a string resource for html error text format
  string sResponseHeader;
  char tempHeader[4096]; 

 
  
  m_HttpData.SetStatusAndReason(559,MG_WCHAR_TO_CHAR(statusMessage));
  sprintf(tempHeader, "%s%s", MapAgentStrings::TextHtml, MapAgentStrings::Utf8Text);
  m_HttpData.AddHeader(MapAgentStrings::ContentTypeKey,tempHeader);

  WriteContent("\r\n"
    "<html>\n<head>\n"
    "<title>%s</title>\n"
    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
    "</head>\n"
    "<body>\n<h2>%s</h2>\n%s\n</body>\n</html>\n",
    MG_WCHAR_TO_CHAR(statusMessage),
    MG_WCHAR_TO_CHAR(shortError),
    MG_WCHAR_TO_CHAR(longError));
  

  MG_CATCH(L"IsapiResponseHandler.SendError")
}
Esempio n. 8
0
void CgiResponseHandler::SendError(MgException* e)
{
    MG_TRY()
    STRING shortError = e->GetExceptionMessage();
    STRING stackTrace = e->GetStackTrace();
    STRING statusMessage = e->GetClassName();
    STRING longError = e->GetDetails();

    //TODO: Use a string resource for html error text format
    printf(MapAgentStrings::StatusHeader, 559, MG_WCHAR_TO_CHAR(statusMessage));
    printf(MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, MapAgentStrings::Utf8Text);
    printf("\r\n"
        "<html>\n<head>\n"
        "<title>%s</title>\n"
        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
        "</head>\n"
        "<body>\n<h2>%s</h2>\n%s\n</body>\n</html>\n",
        MG_WCHAR_TO_CHAR(statusMessage),
        MG_WCHAR_TO_CHAR(shortError),
        MG_WCHAR_TO_CHAR(stackTrace));

    DumpMessage(MG_WCHAR_TO_CHAR(longError));

    MG_CATCH(L"CgiResponseHandler.SendError")
}
Esempio n. 9
0
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Enumerate all the parent Map Definition resources of the specified
/// resources.
///
MgSerializableCollection* MgProxyResourceService::EnumerateParentMapDefinitions(
    MgSerializableCollection* resources)
{
    MgCommand cmd;

    MG_TRY()

    assert(m_connProp != NULL);

    cmd.ExecuteCommand(
        m_connProp,                                         // Connection
        MgCommand::knObject,                                // Return type
        MgResourceService::opIdEnumerateParentMapDefinitions, // Command code
        1,                                                  // Number of arguments
        Resource_Service,                                   // Service ID
        BUILD_VERSION(1,0,0),                               // Operation version
        MgCommand::knObject, resources,                     // Argument #1
        MgCommand::knNone);

    SetWarning(cmd.GetWarningObject());

    MG_CATCH_AND_THROW(L"MgProxyResourceService.EnumerateParentMapDefinitions")

    return (MgSerializableCollection*)cmd.GetReturnValue().val.m_obj;
}
Esempio n. 10
0
///----------------------------------------------------------------------------
/// <summary>
/// Executes the operation.
/// </summary>
///
/// <exceptions>
/// MgException
/// </exceptions>
///----------------------------------------------------------------------------
void MgOpGetPackageStatus::Execute()
{
    ACE_DEBUG((LM_DEBUG, ACE_TEXT("  (%t) MgOpGetPackageStatus::Execute()\n")));

    MG_LOG_OPERATION_MESSAGE(L"GetPackageStatus");

    MG_TRY()

    MG_LOG_OPERATION_MESSAGE_INIT(m_packet.m_OperationVersion, m_packet.m_NumArguments);

    ACE_ASSERT(m_stream != NULL);

    if (1 == m_packet.m_NumArguments)
    {
        STRING packageName;
        m_stream->GetString(packageName);

        BeginExecution();

        MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
        MG_LOG_OPERATION_MESSAGE_ADD_STRING(packageName);
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();

        // Validate operation
        Validate();

        Ptr<MgPackageStatusInformation> statusInfo = m_service->GetPackageStatus(packageName);

        EndExecution(statusInfo);
    }
    else
    {
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();
    }

    if (!m_argsRead)
    {
        throw new MgOperationProcessingException(L"MgOpGetPackageStatus.Execute",
            __LINE__, __WFILE__, NULL, L"", NULL);
    }

    // Successful operation
    MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Success.c_str());

    MG_CATCH(L"MgOpGetPackageStatus.Execute")

    if (mgException != NULL)
    {
        // Failed operation
        MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Failure.c_str());
    }

    // Add admin log entry for operation
    MG_LOG_OPERATION_MESSAGE_ADMIN_ENTRY();

    MG_THROW()
}
Esempio n. 11
0
///----------------------------------------------------------------------------
/// <summary>
/// Executes the operation.
/// </summary>
///
/// <exceptions>
/// MgException
/// </exceptions>
///----------------------------------------------------------------------------
void MgOpSetMaximumLogSize::Execute()
{
    ACE_DEBUG((LM_DEBUG, ACE_TEXT("  (%t) MgOpSetMaximumLogSize::Execute()\n")));

    MG_LOG_OPERATION_MESSAGE(L"SetMaximumLogSize");

    MG_TRY()

    MG_LOG_OPERATION_MESSAGE_INIT(m_packet.m_OperationVersion, m_packet.m_NumArguments);

    ACE_ASSERT(m_stream != NULL);

    if (1 == m_packet.m_NumArguments)
    {
        INT32 size;
        m_stream->GetInt32(size);

        BeginExecution();

        MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();

        // Validate operation
        Validate();

        m_service->SetMaximumLogSize(size);

        EndExecution();
    }
    else
    {
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();
    }

    if (!m_argsRead)
    {
        throw new MgOperationProcessingException(L"MgOpSetMaximumLogSize.Execute",
            __LINE__, __WFILE__, NULL, L"", NULL);
    }

    // Successful operation
    MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Success.c_str());

    MG_CATCH(L"MgOpSetMaximumLogSize.Execute")

    if (mgException != NULL)
    {
        // Failed operation
        MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Failure.c_str());
    }

    // Add admin log entry for operation
    MG_LOG_OPERATION_MESSAGE_ADMIN_ENTRY();

    MG_THROW()
}
Esempio n. 12
0
///////////////////////////////////////////////////////////////////////////
/// \brief
/// Gets the contents of the specified resources.
///
MgStringCollection* MgProxyResourceService::GetResourceContents(MgStringCollection* resources,
        MgStringCollection* preProcessTags)
{
    Ptr<MgStringCollection> resourceContents;

    MG_TRY()

    MgCommand cmd;

    cmd.ExecuteCommand(m_connProp,                      // Connection
                       MgCommand::knObject,                            // Return type expected
                       MgResourceService::opIdGetResourceContents,     // Command Code
                       2,                                              // Count of arguments
                       Resource_Service,                               // Service Id
                       BUILD_VERSION(2,2,0),                           // Operation version
                       MgCommand::knObject, resources,                 // Argument#1
                       MgCommand::knObject, preProcessTags,            // Argument#2
                       MgCommand::knNone);                             // End of argument

    SetWarning(cmd.GetWarningObject());

    resourceContents = (MgStringCollection*)cmd.GetReturnValue().val.m_obj;

    // Decrypt the document if Substitution pre-processing is required.
    if(preProcessTags != NULL && resourceContents != NULL && preProcessTags->GetCount() == resourceContents->GetCount())
    {
        for(INT32 i = 0; i < resourceContents->GetCount(); i ++)
        {
            STRING tag = preProcessTags->GetItem(i);

            if (MgResourcePreProcessingType::Substitution == tag)
            {
                STRING cipherContent = resourceContents->GetItem(i);

                string cipherText, plainText;
                MgUtil::WideCharToMultiByte(cipherContent, cipherText);

                MG_CRYPTOGRAPHY_TRY()

                MgCryptographyUtil cryptoUtil;

                cryptoUtil.DecryptString(cipherText, plainText);

                MG_CRYPTOGRAPHY_CATCH_AND_THROW(L"MgProxyResourceService.GetResourceContents")

                STRING decryptedContent;
                MgUtil::MultiByteToWideChar(plainText, decryptedContent);
                resourceContents->SetItem(i, decryptedContent);
            }
        }
    }

    MG_CATCH_AND_THROW(L"MgProxyResourceService.GetResourceContents")

    return resourceContents.Detach();
}
Esempio n. 13
0
///----------------------------------------------------------------------------
/// <summary>
/// Executes the operation.
/// </summary>
///
/// <exceptions>
/// MgException
/// </exceptions>
///----------------------------------------------------------------------------
void MgOpEnumerateLogs::Execute()
{
    ACE_DEBUG((LM_DEBUG, ACE_TEXT("  (%t) MgOpEnumerateLogs::Execute()\n")));

    MG_LOG_OPERATION_MESSAGE(L"EnumerateLogs");

    MG_TRY()

    MG_LOG_OPERATION_MESSAGE_INIT(m_packet.m_OperationVersion, m_packet.m_NumArguments);

    ACE_ASSERT(m_stream != NULL);

    if (0 == m_packet.m_NumArguments)
    {
        BeginExecution();

        MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();

        // Validate operation
        Validate();

        Ptr<MgPropertyCollection> logs = m_service->EnumerateLogs();

        EndExecution(logs);
    }
    else
    {
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
        MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();
    }

    if (!m_argsRead)
    {
        throw new MgOperationProcessingException(L"MgOpEnumerateLogs.Execute",
            __LINE__, __WFILE__, NULL, L"", NULL);
    }

    // Successful operation
    MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Success.c_str());

    MG_CATCH(L"MgOpEnumerateLogs.Execute")

    if (mgException != NULL)
    {
        // Failed operation
        MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Failure.c_str());
    }

    // Add admin log entry for operation
    MG_LOG_OPERATION_MESSAGE_ADMIN_ENTRY();

    MG_THROW()
}
Esempio n. 14
0
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns tagged data for the specified resource.
/// </summary>
/// <param name="resource">
/// Resource identifier describing the resource.
/// </param>
/// <param name="dataName">
/// Name for data.  Either a resource-unique stream name for streams or a
/// resource-unique file name for file data.
/// </param>
/// <param name="preProcessTags">
/// Pre-processing to apply to resource data before returning.  An empty
/// string indicate no pre-processing. See MgResourcePreProcessingType for
/// a list of supported pre-processing tags.
/// </param>
/// <returns>
/// MgByteReader containing the previously updated or added tagged data.
/// </returns>
/// EXCEPTIONS:
/// MgRepositoryNotOpenException
///
/// MgResourceDataNotFoundException
/// MgInvalidResourceTypeException
///
MgByteReader* MgProxyResourceService::GetResourceData(
    MgResourceIdentifier* resource, CREFSTRING dataName,
    CREFSTRING preProcessTags)
{
    Ptr<MgByteReader> byteReader;

    MG_TRY()

    MgCommand cmd;

    cmd.ExecuteCommand(m_connProp,
                       MgCommand::knObject,
                       MgResourceService::opIdGetResourceData,
                       3,
                       Resource_Service,
                       BUILD_VERSION(1,0,0),
                       MgCommand::knObject, resource,
                       MgCommand::knString, &dataName,
                       MgCommand::knString, &preProcessTags,
                       MgCommand::knNone);

    SetWarning(cmd.GetWarningObject());

    byteReader = (MgByteReader*)cmd.GetReturnValue().val.m_obj;

    // Decrypt the document if Substitution pre-processing is required.

    if (MgResourcePreProcessingType::Substitution == preProcessTags
            && byteReader != NULL)
    {
        STRING mimeType = byteReader->GetByteSource()->GetMimeType();
        string cipherText, plainText;

        byteReader->ToStringUtf8(cipherText);

        MG_CRYPTOGRAPHY_TRY()

        MgCryptographyUtil cryptoUtil;

        cryptoUtil.DecryptString(cipherText, plainText);

        MG_CRYPTOGRAPHY_CATCH_AND_THROW(L"MgProxyResourceService.GetResourceData")

        Ptr<MgByteSource> byteSource = new MgByteSource(
            (BYTE_ARRAY_IN)plainText.c_str(), (INT32)plainText.length());

        byteSource->SetMimeType(mimeType);
        byteReader = byteSource->GetReader();
    }

    MG_CATCH_AND_THROW(L"MgProxyResourceService.GetResourceData")

    return byteReader.Detach();
}
Esempio n. 15
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Update the specified session with the current operation information.
///
void MgSessionManager::UpdateCurrentOperationInfo(const MgConnection& connection)
{
    ACE_MT(ACE_GUARD(ACE_Recursive_Thread_Mutex, ace_mon, sm_mutex));

    MG_TRY()

    MgSessionInfo* sessionInfo = sm_sessionCache->GetSessionInfo(connection.GetSessionId());
    assert(NULL != sessionInfo);

    sessionInfo->SetOperationInfo(connection);

    MG_CATCH_AND_RELEASE()
}
Esempio n. 16
0
//////////////////////////////////////////////////////////////////
/// <summary>
/// Releases all the resources of feature reader.
/// This must be called when user is done with Feature Reader
/// <returns>Nothing</returns>
void MgProxySqlDataReader::Close()
{
    if (m_serverSqlDataReader != L"")
    {
        MG_TRY()

        m_service->CloseSqlReader(m_serverSqlDataReader);
        m_serverSqlDataReader = L"";

        MG_CATCH(L"MgProxySqlDataReader.Close")

        // We do not rethrow the exception while destructing the object. Even if we had problem
        // disposing this feature reader, it will automatically get collected after time out.
    }
Esempio n. 17
0
void Initialize()
{
    char* path = getenv(MapAgentStrings::PhysicalPath);
    if (NULL != path && strlen(path) > 0)
    {
        gConfigPath = MgUtil::MultiByteToWideChar(string(path));
    }
    else
    {
#if defined _WIN32
        // IIS 6.0 does not honour APPL_PHYSICAL_PATH.  Use exe path.
        wchar_t modPath[_MAX_PATH+1];
        memset(modPath, 0, sizeof(wchar_t)*(_MAX_PATH+1));
        if (GetModuleFileName(NULL, modPath, _MAX_PATH) > 4)
        {
            wchar_t* lastSlash = wcsrchr(modPath, L'\\');
            if (NULL == lastSlash)
            {
                lastSlash = wcsrchr(modPath, L'/');
            }
            if (NULL != lastSlash)
            {
                lastSlash++;
                *lastSlash = L'\0';
                if (NULL != wcsstr(modPath, L"\\\\?\\"))
                {
                    // skip past '\\?\' at front of string.
                    gConfigPath = &(modPath[4]);
                }
                else
                {
                    gConfigPath = modPath;
                }
            }
        }
#endif

    }
    STRING configFile = gConfigPath;
    configFile.append(MapAgentStrings::WebConfig);

    string pathName = MgUtil::WideCharToMultiByte(configFile);
    DumpMessage("Loading configuration file: %s",pathName.c_str());

    MG_TRY()

    MgInitializeWebTier(configFile);

    MG_CATCH_AND_THROW(L"FastCgiAgent.Initialize");
}
Esempio n. 18
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Handle the Resource Change Notification event.
/// Any tile cache associated with the specified Map Definition resources
/// will be cleared.
///
bool MgdTileService::NotifyResourcesChanged(MgSerializableCollection* resources, bool strict)
{
    bool success = true;

    if (NULL != resources)
    {
        INT32 numResources = resources->GetCount();

        if (numResources > 0)
        {
            for (INT32 i = 0; i < numResources; ++i)
            {
                Ptr<MgSerializable> serializableObj = resources->GetItem(i);
                MgResourceIdentifier* resource =
                    dynamic_cast<MgResourceIdentifier*>(serializableObj.p);
                ACE_ASSERT(NULL != resource);

                if (NULL != resource && resource->IsResourceTypeOf(MgResourceType::MapDefinition))
                {
                    MG_TRY()

                    // clear any cached mgmap objects
                    ClearMapCache(resource->ToString());

                    // clear any tile cache associated with this map
                    m_tileCache->Clear(resource);

                    MG_CATCH(L"MgdTileService.NotifyResourcesChanged")

                    if (NULL != mgException.p)
                    {
                        success = false;

                        if (strict)
                        {
                            MG_THROW();
                        }
                        /*
                        else
                        {
                            MgdLogManager* logManager = MgdLogManager::GetInstance();
                            ACE_ASSERT(NULL != logManager);
                            logManager->LogSystemErrorEntry(mgException.p);
                        }*/
                    }
                }
            }
        }
Esempio n. 19
0
File: Layer.cpp Progetto: asir6/Colt
//////////////////////////////////////////////////////////////
// Parse the layer definition XML and extracts scale ranges,
// feature source and feature class from it
//
void MgLayer::GetLayerInfoFromDefinition(MgResourceService* resourceService)
{
    MgLayerBase::GetLayerInfoFromDefinition(resourceService);

    if(m_initIdProps && resourceService != NULL)
    {
        MG_TRY()

        // Generate Id field information for feature sources
        m_idProps.clear();
        if (!m_featureName.empty())
        {
            // If we cannot pull the identity properties, silently ignore it.
            try
            {
                //TODO: Pull site connection directly from resource service
                Ptr<MgUserInformation> userInfo = resourceService->GetUserInfo();
                Ptr<MgSiteConnection> conn = new MgSiteConnection();
                conn->Open(userInfo);

                Ptr<MgFeatureService> featureService = dynamic_cast<MgFeatureService*>(conn->CreateService(MgServiceType::FeatureService));
                Ptr<MgResourceIdentifier> resId = new MgResourceIdentifier(m_featureSourceId);

                // If the class name is fully qualified (prefixed with a schema name),
                // then use it to determine the schema name.
                STRING className;
                STRING schemaName;
                ParseFeatureName(featureService, className, schemaName);

                // Get the identity properties
                Ptr<MgStringCollection> classNames = new MgStringCollection();
                classNames->Add(className);
                Ptr<MgClassDefinitionCollection> classDefs = featureService->GetIdentityProperties(resId, schemaName, classNames);
                if (NULL != classDefs.p && classDefs->GetCount() == 1)
                {
                    Ptr<MgClassDefinition> classDef = classDefs->GetItem(0);
                    PopulateIdentityProperties(classDef);
                }
            }
            catch (MgException* e)
            {
                e->Release();
                // Do nothing here.  A failure to pull selection id's is not critical at this point
            }
        }
        MG_CATCH_AND_THROW(L"MgLayer.GetLayerInfoFromDefinition")
    }
Esempio n. 20
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Ends the resource package loading process.
///
void MgdResourcePackageLoader::End(MgException* except)
{
    MG_TRY()

    // Close the package file.
    m_zipFileReader.reset(NULL);

    /*
    if (m_packageLogWriter != NULL)
    {
        MgPackageStatusInformation& statusInfo = m_packageLogWriter->GetStatusInfo();

        statusInfo.SetPackageDescription(m_manifestParser.GetDescription());
    }*/

    // Update the status information.
    UpdateStatus(except);

    MG_CATCH_AND_RELEASE()
}
Esempio n. 21
0
void MgServerAdmin::UnregisterServicesOnServers(
    MgSerializableCollection* serverInfoList)
{
    MG_TRY()

    MgCommand cmd;

    cmd.ExecuteCommand(m_connProp,                                              // Connection
                        MgCommand::knVoid,                                      // Return type
                        MgServerAdminServiceOpId::UnregisterServicesOnServers,  // Command code
                        1,                                                      // Number of arguments
                        ServerAdmin_Service,                                    // Service ID
                        BUILD_VERSION(1,0,0),                                   // Operation version
                        MgCommand::knObject, serverInfoList,                    // Argument #1
                        MgCommand::knNone );

    SetWarning(cmd.GetWarningObject());

    MG_CATCH_AND_THROW(L"MgServerAdmin.UnregisterServicesOnServers")
}
Esempio n. 22
0
void MgSiteConnection::Initialize()
{
    MG_TRY()

    // get instanced MgConfiguration for local use
    m_config = MgConfiguration::GetInstance();

    m_isServer     = false;
    m_isSiteServer = false;
    m_isWebTier    = false;
    m_http         = IsHttpConnection();

    if (!m_http)
    {
        m_isServer     = IsServer();
        m_isSiteServer = IsSiteServer();
        m_isWebTier    = IsWebTier();
    }

    MG_CATCH_AND_THROW(L"MgSiteConnection::Initialize")
}
Esempio n. 23
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Send a resource change notification.
///
void MgServerAdmin::NotifyResourcesChanged(MgSerializableCollection* resources)
{
    MG_TRY()

    assert(m_connProp != NULL);
    MgCommand cmd;

    cmd.ExecuteCommand(
        m_connProp,                                         // Connection
        MgCommand::knVoid,                                  // Return type
        MgServerAdminServiceOpId::NotifyResourcesChanged,   // Command code
        1,                                                  // Number of arguments
        ServerAdmin_Service,                                // Service ID
        BUILD_VERSION(1,0,0),                               // Operation version
        MgCommand::knObject, resources,                     // Argument #1
        MgCommand::knNone);

    SetWarning(cmd.GetWarningObject());

    MG_CATCH_AND_THROW(L"MgServerAdmin.NotifyResourcesChanged")
}
Esempio n. 24
0
OrientedPolyPolygon & OrientedPolyPolygon::operator=(const OrientedPolyPolygon &orientedPolyPolygon)
{
    if (this != &orientedPolyPolygon)
    {
        Cleanup();

        m_nBoundaries = orientedPolyPolygon.m_nBoundaries;
        m_maxBoundaries = orientedPolyPolygon.m_maxBoundaries;
        m_totalVertices = orientedPolyPolygon.m_totalVertices;
        m_extentOfBoundaries = orientedPolyPolygon.m_extentOfBoundaries;

        MG_TRY()

        m_nBoundaryVerts = new int[m_maxBoundaries];
        m_boundaryExt = new OpsFloatExtent[m_maxBoundaries];
        m_boundaries = new OpsFloatPoint *[m_maxBoundaries];

        for (int i = 0; i < m_nBoundaries; i++)
        {
            m_nBoundaryVerts[i] = orientedPolyPolygon.m_nBoundaryVerts[i];
            m_boundaryExt[i] = orientedPolyPolygon.m_boundaryExt[i];
            m_boundaries[i] = new OpsFloatPoint[m_nBoundaryVerts[i]];

            for (int j = 0; j < m_nBoundaryVerts[i]; j++)
            {
                m_boundaries[i][j] = orientedPolyPolygon.m_boundaries[i][j];
            }
        }

        MG_CATCH(L"OrientedPolyPolygon.operator=")

        if (mgException != 0) // mgException is defined in MG_TRY() macro
        {
            Cleanup();
        }

        MG_THROW()

    }
Esempio n. 25
0
void MgdTileService::ClearCache(MgdMap* map)
{
    MG_LOG_OPERATION_MESSAGE(L"ClearCache");

    MG_TRY()

    Ptr<MgResourceIdentifier> resourceId;
    if (NULL != map)
        resourceId = map->GetMapDefinition();
    MG_LOG_OPERATION_MESSAGE_INIT(MG_API_VERSION(1, 0, 0), 1);
    MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
    MG_LOG_OPERATION_MESSAGE_ADD_STRING((NULL == resourceId) ? L"MgResourceIdentifier" : resourceId->ToString().c_str());
    MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();

    if (NULL == map)
        throw new MgNullArgumentException(L"MgdTileService.ClearCache", __LINE__, __WFILE__, NULL, L"", NULL);

    ClearMapCache(resourceId->ToString());

    m_tileCache->Clear(map);

    // Successful operation
    MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Success.c_str());

    MG_CATCH(L"MgdTileService::ClearCache")

    if (mgException != NULL)
    {
        // Failed operation
        MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Failure.c_str());
        MG_DESKTOP_LOG_EXCEPTION();
    }

    // Add access log entry for operation
    MG_LOG_OPERATION_MESSAGE_ACCESS_ENTRY();

    MG_THROW()
}
Esempio n. 26
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Gets the pointer to a process-wide MgUnmanagedDataManager.
///
MgUnmanagedDataManager* MgUnmanagedDataManager::GetInstance()
{
    MG_TRY()

    ACE_TRACE("MgUnmanagedDataManager::GetInstance");

    if (MgUnmanagedDataManager::sm_unmanagedDataManager == NULL)
    {
        // Perform Double-Checked Locking Optimization.
        ACE_MT(ACE_GUARD_RETURN(ACE_Recursive_Thread_Mutex, ace_mon, *ACE_Static_Object_Lock::instance(), NULL));

        if (MgUnmanagedDataManager::sm_unmanagedDataManager == NULL)
        {
            MgUnmanagedDataManager::sm_unmanagedDataManager = new MgUnmanagedDataManager;
        }
    }

    MG_CATCH_AND_THROW(L"MgUnmanagedDataManager.GetInstance")

    // To avoid overheads and maintain thread safety,
    // do not assign this returned static singleton to a Ptr object.
    return MgUnmanagedDataManager::sm_unmanagedDataManager;
}
Esempio n. 27
0
// Helper method to get the layout properties from the PrintLayout xml resource.
void MgPrintLayout::GetLayoutPropertiesFromXml(MgXmlUtil* pXmlUtil)
{
    CHECKNULL(pXmlUtil, L"MgPrintLayout.GetLayoutPropertiesFromXml()");

    MG_TRY()

    // Retrieve values from the xml document
    DOMElement* root = pXmlUtil->GetRootNode();
    CHECKNULL(root, L"MgPrintLayout.GetLayoutProperitesFromXml()");

//  DOMElement* pageProperties = pXmlUtil->GetElementNode(root, "PageProperties");

    DOMElement* backgroundColor = pXmlUtil->GetElementNode(root, "BackgroundColor");

    wstring szRed;
    pXmlUtil->GetElementValue(backgroundColor, "Red", szRed);

    wstring szGreen;
    pXmlUtil->GetElementValue(backgroundColor, "Green", szGreen);

    wstring szBlue;
    pXmlUtil->GetElementValue(backgroundColor, "Blue", szBlue);

    DOMElement* layoutProperties = pXmlUtil->GetElementNode(root, "LayoutProperties");

    wstring szShowTitle;
    pXmlUtil->GetElementValue(layoutProperties, "ShowTitle", szShowTitle, false);

    wstring szShowLegend;
    pXmlUtil->GetElementValue(layoutProperties, "ShowLegend", szShowLegend, false);

    wstring szShowScalebar;
    pXmlUtil->GetElementValue(layoutProperties, "ShowScaleBar", szShowScalebar, false);

    wstring szShowNorthArrow;
    pXmlUtil->GetElementValue(layoutProperties, "ShowNorthArrow", szShowNorthArrow, false);

    wstring szShowUrl;
    pXmlUtil->GetElementValue(layoutProperties, "ShowURL", szShowUrl, false);

    wstring szShowDateTime;
    pXmlUtil->GetElementValue(layoutProperties, "ShowDateTime", szShowDateTime, false);

    wstring szShowCustomLogos;
    pXmlUtil->GetElementValue(layoutProperties, "ShowCustomLogos", szShowCustomLogos, false);

    wstring szShowCustomText;
    pXmlUtil->GetElementValue(layoutProperties, "ShowCustomText", szShowCustomText, false);

    DOMNode* customLogosNode = pXmlUtil->GetElementNode(root, "CustomLogos", false);
    if (NULL != customLogosNode)
    {
        DOMNodeList* customLogosNodeList = pXmlUtil->GetNodeList(customLogosNode, "Logo");
        if (NULL != customLogosNodeList)
        {
            for (XMLSize_t i = 0; i < customLogosNodeList->getLength(); ++i)
            {
                MgCustomLogoInfo logoInfo;
                wstring positionX;
                wstring positionY;
                wstring positionUnits;
                wstring resId;
                wstring name;
                wstring sizeWidth;
                wstring sizeHeight;
                wstring sizeUnits;
                wstring rotation;

                DOMNode* logoNode = customLogosNodeList->item(i);
                DOMNode* logoPositionNode = pXmlUtil->GetElementNode(logoNode, "Position", false);
                if (NULL != logoPositionNode)
                {
                    pXmlUtil->GetElementValue(logoPositionNode, "Left", positionX, false);
                    pXmlUtil->GetElementValue(logoPositionNode, "Bottom", positionY, false);
                    pXmlUtil->GetElementValue(logoPositionNode, "Units", positionUnits, false);
                    if (!positionUnits.empty()
                        && positionUnits != L"meters" && positionUnits != L"inches" && positionUnits != L"percent")
                    {
                        // invalid print layout position units
                        throw new MgInvalidPrintLayoutPositionUnitsException(L"MgPrintLayout.GetLayoutPropertiesFromXml", __LINE__, __WFILE__, NULL, L"", NULL);
                    }
                }
                pXmlUtil->GetElementValue(logoNode, "ResourceId", resId, false);
                pXmlUtil->GetElementValue(logoNode, "Name", name, false);
                DOMNode* logoSizeNode = pXmlUtil->GetElementNode(logoNode, "Size", false);
                if (NULL != logoSizeNode)
                {
                    pXmlUtil->GetElementValue(logoSizeNode, "Width", sizeWidth, false);
                    pXmlUtil->GetElementValue(logoSizeNode, "Height", sizeHeight, false);
                    pXmlUtil->GetElementValue(logoSizeNode, "Units", sizeUnits, false);
                    if (!sizeUnits.empty()
                        && sizeUnits != L"inches" && sizeUnits != L"meters")
                    {
                        // invalid print layout size units
                        throw new MgInvalidPrintLayoutSizeUnitsException(L"MgPrintLayout.GetLayoutPropertiesFromXml", __LINE__, __WFILE__, NULL, L"", NULL);
                    }
                }
                pXmlUtil->GetElementValue(logoNode, "Rotation", rotation, false);
                logoInfo.SetX( MgUtil::StringToDouble(positionX) );
                logoInfo.SetY( MgUtil::StringToDouble(positionY) );
                logoInfo.SetPositionUnits( positionUnits );
                logoInfo.SetResourceId( resId );
                logoInfo.SetName( name );
                logoInfo.SetWidth( MgUtil::StringToDouble(sizeWidth) );
                logoInfo.SetHeight( MgUtil::StringToDouble(sizeHeight) );
                logoInfo.SetSizeUnits( sizeUnits );
                logoInfo.SetRotation( MgUtil::StringToDouble(rotation) );

                CustomLogos().push_back(logoInfo);
            }
        }
    }

    DOMNode* customTextNode = pXmlUtil->GetElementNode(root, "CustomText", false);
    if (NULL != customTextNode)
    {
        DOMNodeList* customTextNodeList = pXmlUtil->GetNodeList(customTextNode, "Text");
        if (NULL != customTextNodeList)
        {
            for (XMLSize_t i = 0; i < customTextNodeList->getLength(); ++i)
            {
                MgCustomTextInfo textInfo;
                wstring positionX;
                wstring positionY;
                wstring positionUnits;
                wstring value;
                wstring fontName;
                wstring fontHeight;
                wstring fontSizeUnits;

                DOMNode* textNode = customTextNodeList->item(i);
                DOMNode* textPositionNode = pXmlUtil->GetElementNode(textNode, "Position", false);
                if (NULL != textPositionNode)
                {
                    pXmlUtil->GetElementValue(textPositionNode, "Left", positionX, false);
                    pXmlUtil->GetElementValue(textPositionNode, "Bottom", positionY, false);
                    pXmlUtil->GetElementValue(textPositionNode, "Units", positionUnits, false);
                    if (!positionUnits.empty()
                        && positionUnits != L"percent" && positionUnits != L"meters" && positionUnits != L"inches")
                    {
                        // invalid print layout position units
                        throw new MgInvalidPrintLayoutPositionUnitsException(L"MgPrintLayout.GetLayoutPropertiesFromXml", __LINE__, __WFILE__, NULL, L"", NULL);
                    }
                }
                DOMNode* fontNode = pXmlUtil->GetElementNode(textNode, "Font", false);
                if (NULL != fontNode)
                {
                    pXmlUtil->GetElementValue(fontNode, "Name", fontName, false);
                    pXmlUtil->GetElementValue(fontNode, "Height", fontHeight, false);
                    pXmlUtil->GetElementValue(fontNode, "Units", fontSizeUnits, false);
                    if (!fontSizeUnits.empty()
                        && fontSizeUnits != L"points" && fontSizeUnits != L"meters" && fontSizeUnits != L"inches")
                    {
                        // invalid print layout font size units
                        throw new MgInvalidPrintLayoutFontSizeUnitsException(L"MgPrintLayout.GetLayoutPropertiesFromXml", __LINE__, __WFILE__, NULL, L"", NULL);
                    }
                }
                pXmlUtil->GetElementValue(textNode, "Value", value, false);
                textInfo.SetX( MgUtil::StringToDouble( positionX ) );
                textInfo.SetY( MgUtil::StringToDouble( positionY ) );
                textInfo.SetPositionUnits( positionUnits );
                textInfo.SetValue( value );
                textInfo.SetFontName( fontName );
                textInfo.SetFontHeight( MgUtil::StringToDouble( fontHeight ) );
                textInfo.SetSizeUnits( fontSizeUnits );

                CustomText().push_back(textInfo);
            }
        }
    }

    // Set MgPrintLayout values
    INT32 nRed = MgUtil::StringToInt32( szRed );
    INT32 nGreen = MgUtil::StringToInt32( szGreen );
    INT32 nBlue = MgUtil::StringToInt32( szBlue );
    m_bgColor = new MgColor(nRed, nGreen, nBlue, 255);

    ShowTitle() = MgUtil::StringToBoolean( szShowTitle );

    ShowLegend() = MgUtil::StringToBoolean( szShowLegend );

    ShowScalebar() = MgUtil::StringToBoolean( szShowScalebar );

    ShowNorthArrow() = MgUtil::StringToBoolean( szShowNorthArrow );

    ShowUrl() = MgUtil::StringToBoolean( szShowUrl );

    ShowDateTime() = MgUtil::StringToBoolean( szShowDateTime );

    ShowCustomLogos() = MgUtil::StringToBoolean( szShowCustomLogos );

    ShowCustomText() = MgUtil::StringToBoolean( szShowCustomText );

    MG_CATCH_AND_THROW(L"MgPrintLayout.GetLayoutPropertiesFromXml")
}
Esempio n. 28
0
///////////////////////////////////////////////////////////////////////////////
// look for the tile in the tilecache first
MgByteReader* MgdTileService::GetTile(MgdMap* map,
                                      CREFSTRING baseMapLayerGroupName,
                                      INT32 tileColumn,
                                      INT32 tileRow)
{
    Ptr<MgByteReader> ret;
    FILE* lockFile = NULL;
    STRING tilePathname, lockPathname;

    MG_LOG_OPERATION_MESSAGE(L"GetTile");

    MG_TRY()

    Ptr<MgResourceIdentifier> mapId;
    if (NULL != map)
        mapId = map->GetMapDefinition();
    MG_LOG_OPERATION_MESSAGE_INIT(MG_API_VERSION(1, 0, 0), 4);
    MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
    MG_LOG_OPERATION_MESSAGE_ADD_STRING((NULL == mapId) ? L"MgResourceIdentifier" : mapId->ToString().c_str());
    MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR();
    MG_LOG_OPERATION_MESSAGE_ADD_STRING(baseMapLayerGroupName.c_str());
    MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR();
    MG_LOG_OPERATION_MESSAGE_ADD_INT32(tileColumn);
    MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR();
    MG_LOG_OPERATION_MESSAGE_ADD_INT32(tileRow);
    MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();

    if (NULL == map || baseMapLayerGroupName.empty())
    {
        throw new MgNullArgumentException(L"MgdTileService.GetTile",
                                          __LINE__, __WFILE__, NULL, L"", NULL);
    }

    // find the finite display scale closest to the requested map scale
    double scale = map->GetViewScale();
    INT32 scaleIndex = map->FindNearestFiniteDisplayScaleIndex(scale);

    // if we don't find a nearest scale then something is wrong with the map
    if (scaleIndex < 0)
    {
        throw new MgInvalidMapDefinitionException(L"MgdTileService.GetTile",
                __LINE__, __WFILE__, NULL, L"", NULL);
    }

    // Detect the lock file to see if another thread is creating the tile file.
    m_tileCache->GeneratePathnames(map, scaleIndex, baseMapLayerGroupName,
                                   tileColumn, tileRow, tilePathname, lockPathname, false);

    // If there is a dangling lock file, then attempt to remove it.
    if (DetectTileLockFile(lockPathname))
    {
        // TODO: Handle the exception by displaying a tile with an error message?
        MgFileUtil::DeleteFile(lockPathname, true);
    }

    // try getting the tile from the cache
    ret = m_tileCache->Get(tilePathname);

    // if the reader is NULL then the tile wasn't in the cache and we
    // need to generate it
    while (NULL == ret)
    {
        {
            // Attemp to lock the tile file.
            ACE_MT(ACE_GUARD_RETURN(ACE_Recursive_Thread_Mutex, ace_mon, sm_MgdMutex, NULL));

            // Bail out if the tile file has been locked for so long.
            if (DetectTileLockFile(lockPathname))
            {
                MgStringCollection arguments;
                arguments.Add(lockPathname);

                throw new MgFileIoException(L"MgdTileService.GetTile",
                                            __LINE__, __WFILE__, &arguments, L"MgUnableToLockTileFile", NULL);
            }

            // try getting the tile from the cache
            ret = m_tileCache->Get(tilePathname);

            if (NULL != ret)
            {
                break;
            }

            // Create the lock file and close it right away.
            m_tileCache->CreateFullPath(map, scaleIndex, baseMapLayerGroupName, tileColumn, tileRow);
            lockFile = ACE_OS::fopen(MG_WCHAR_TO_TCHAR(lockPathname), ACE_TEXT("wb"));

            if (NULL == lockFile)
            {
                MgStringCollection arguments;
                arguments.Add(lockPathname);

                throw new MgFileIoException(L"MgdTileService.GetTile",
                                            __LINE__, __WFILE__, &arguments, L"MgUnableToOpenLockFile", NULL);
            }
            else
            {
                ACE_OS::fclose(lockFile);
            }
        }

        // Render the tile and cache it.
        ret = GetTile(tilePathname, map, scaleIndex, baseMapLayerGroupName, tileColumn, tileRow);
        break;
    }

    // Successful operation
    MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Success.c_str());

    MG_CATCH(L"MgdTileService::GetTile")

    if (mgException != NULL)
    {
        // Failed operation
        MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Failure.c_str());
        MG_DESKTOP_LOG_EXCEPTION();
    }

    if (NULL != lockFile)
    {
        MgFileUtil::DeleteFile(lockPathname, false);
    }

    // Add access log entry for operation
    MG_LOG_OPERATION_MESSAGE_ACCESS_ENTRY();

    MG_THROW()

    return ret.Detach();
}
Esempio n. 29
0
///////////////////////////////////////////////////////////////////////////////
// Create tilename from mapDefinition, scaleIndex, row, and column.
// Remove lockfile, look for the tile in the cache, if not in cache create
// lockfile and look for map in mapcache.
MgByteReader* MgdTileService::GetTile(MgResourceIdentifier* mapDefinition,
                                      CREFSTRING baseMapLayerGroupName,
                                      INT32 tileColumn,
                                      INT32 tileRow,
                                      INT32 scaleIndex)
{
    Ptr<MgByteReader> ret;
    FILE* lockFile = NULL;
    STRING tilePathname, lockPathname;

    MG_LOG_OPERATION_MESSAGE(L"GetTile");

    MG_TRY()

    MG_LOG_OPERATION_MESSAGE_INIT(MG_API_VERSION(1, 0, 0), 5);
    MG_LOG_OPERATION_MESSAGE_PARAMETERS_START();
    MG_LOG_OPERATION_MESSAGE_ADD_STRING((NULL == mapDefinition) ? L"MgResourceIdentifier" : mapDefinition->ToString().c_str());
    MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR();
    MG_LOG_OPERATION_MESSAGE_ADD_STRING(baseMapLayerGroupName.c_str());
    MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR();
    MG_LOG_OPERATION_MESSAGE_ADD_INT32(tileColumn);
    MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR();
    MG_LOG_OPERATION_MESSAGE_ADD_INT32(tileRow);
    MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR();
    MG_LOG_OPERATION_MESSAGE_ADD_INT32(scaleIndex);
    MG_LOG_OPERATION_MESSAGE_PARAMETERS_END();

    if (NULL == mapDefinition || baseMapLayerGroupName.empty())
    {
        throw new MgNullArgumentException(L"MgdTileService.GetTile",
                                          __LINE__, __WFILE__, NULL, L"", NULL);
    }

    if (scaleIndex < 0)
    {
        STRING buffer;
        MgUtil::Int32ToString(scaleIndex, buffer);

        MgStringCollection arguments;
        arguments.Add(L"5");
        arguments.Add(buffer);

        throw new MgInvalidArgumentException(L"MgdTileService.GetTile",
                                             __LINE__, __WFILE__, &arguments, L"MgInvalidScaleIndex", NULL);
    }

    // get the service from our helper method
    Ptr<MgResourceService> resourceService = GetResourceServiceForMapDef(mapDefinition,
            L"MgdTileService.GetTile");
    // Generate tile and lock pathnames.
    m_tileCache->GeneratePathnames(mapDefinition, scaleIndex, baseMapLayerGroupName,
                                   tileColumn, tileRow, tilePathname, lockPathname, false);

    // If there is a dangling lock file, then attempt to remove it.
    if (DetectTileLockFile(lockPathname))
    {
        // TODO: Handle the exception by displaying a tile with an error message?
        MgFileUtil::DeleteFile(lockPathname, true);
    }

    // try getting the tile from the cache
    ret = m_tileCache->Get(tilePathname);

    // if the reader is NULL then the tile wasn't in the cache and we
    // need to generate it
    while (NULL == ret)
    {
        // Attempt use a cached & serialized MgMap object
        Ptr<MgMemoryStreamHelper> cachedMap;
        STRING mapString = mapDefinition->ToString();
        Ptr<MgdMap> map;

        // Protect the serialized MgMap cache with a MgdMutex.  Stream reading is not
        // thread safe so we need to deserialize the map within the MgdMutex to ensure
        // that a Rewind() is not called in the middle of a Deserialize().
        // Lockfile test and creation is in same protected scope.
        {
            // Attempt to lock the tile file.
            ACE_MT(ACE_GUARD_RETURN(ACE_Recursive_Thread_Mutex, ace_mon, sm_MgdMutex, NULL));

            // Bail out if the tile file has been locked for so long.
            if (DetectTileLockFile(lockPathname))
            {
                MgStringCollection arguments;
                arguments.Add(lockPathname);

                throw new MgFileIoException(L"MgdTileService.GetTile",
                                            __LINE__, __WFILE__, &arguments, L"MgUnableToLockTileFile", NULL);
            }

            // try getting the tile from the cache
            ret = m_tileCache->Get(tilePathname);

            if (NULL != ret)
            {
                break;  // tile was in tileCache .. done.
            }

            // Create the lock file and close it right away.
            m_tileCache->CreateFullPath(mapDefinition, scaleIndex, baseMapLayerGroupName, tileColumn, tileRow);
            lockFile = ACE_OS::fopen(MG_WCHAR_TO_TCHAR(lockPathname), ACE_TEXT("wb"));

            if (NULL == lockFile)
            {
                MgStringCollection arguments;
                arguments.Add(lockPathname);

                throw new MgFileIoException(L"MgdTileService.GetTile",
                                            __LINE__, __WFILE__, &arguments, L"MgUnableToOpenLockFile", NULL);
            }
            else
            {
                ACE_OS::fclose(lockFile);
            }

            MapCache::const_iterator iter = sm_mapCache.find(mapString);
            if (sm_mapCache.end() != iter)
            {
                cachedMap = SAFE_ADDREF((*iter).second);
                cachedMap->Rewind();
                Ptr<MgStream> stream = new MgStream(cachedMap);
                map = new MgdMap();
                map->Deserialize(stream);
            }
            else
            {
                /*Ptr<MgSiteConnection> siteConn = new MgSiteConnection();
                Ptr<MgUserInformation> userInfo = MgUserInformation::GetCurrentUserInfo();
                siteConn->Open(userInfo);
                map = new MgMap(siteConn);
                map->Create(resourceService, mapDefinition, mapString);*/
                map = new MgdMap(mapDefinition, mapString);
                cachedMap = new MgMemoryStreamHelper();
                Ptr<MgStream> stream = new MgStream(cachedMap);
                map->Serialize(stream);
                if ((INT32)sm_mapCache.size() >= sm_mapCacheSize)
                {
                    ClearMapCache(L"");
                }
                sm_mapCache[mapString] = SAFE_ADDREF((MgMemoryStreamHelper*)cachedMap);
            }
        }   // end of MgdMutex scope

        double scale = map->GetFiniteDisplayScaleAt(scaleIndex);
        map->SetViewScale(scale);

        // Render the tile and cache it.
        ret = GetTile(tilePathname, map, scaleIndex, baseMapLayerGroupName, tileColumn, tileRow);
        break;
    }

    // Successful operation
    MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Success.c_str());

    MG_CATCH(L"MgdTileService::GetTile")

    if (mgException != NULL)
    {
        // Failed operation
        MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Failure.c_str());
        MG_DESKTOP_LOG_EXCEPTION();
    }

    if (NULL != lockFile)
    {
        MgFileUtil::DeleteFile(lockPathname, false);
    }

    // Add access log entry for operation
    MG_LOG_OPERATION_MESSAGE_ACCESS_ENTRY();

    MG_THROW()

    return ret.Detach();
}
Esempio n. 30
0
void CgiResponseHandler::SendResponse(MgHttpResponse* response)
{
    MG_TRY()

    Ptr<MgHttpResult> result = response->GetResult();
    STATUS status = result->GetStatusCode();
    if (status != 200)
    {
        STRING statusMessage = result->GetHttpStatusMessage();
        if (statusMessage == MapAgentStrings::FailedAuth1 ||
            statusMessage == MapAgentStrings::FailedAuth2)
        {
            RequestAuth();
        }
        else
        {
            //TODO: Use a resource for the HTML error message
            STRING shortError = result->GetErrorMessage();
            STRING longError = result->GetDetailedErrorMessage();
            printf(MapAgentStrings::StatusHeader, status, MG_WCHAR_TO_CHAR(statusMessage));
            printf(MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, "");
            printf("\r\n"
                "<html>\n<head>\n"
                "<title>%s</title>\n"
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
                "</head>\n"
                "<body>\n<h2>%s</h2>\n%s\n</body>\n</html>\n",
                MG_WCHAR_TO_CHAR(statusMessage),
                MG_WCHAR_TO_CHAR(shortError),
                MG_WCHAR_TO_CHAR(longError));

            DumpMessage(MG_WCHAR_TO_CHAR(longError));
        }
    }
    else
    {
        DumpMessage(MapAgentStrings::StatusOkHeader);

        // Status was ok.  Send the real result back.
        STRING contentType = result->GetResultContentType();
        STRING stringVal;

        printf(MapAgentStrings::StatusOkHeader);
        if (contentType.length() > 0)
        {
            // If we are returning text, state that it is utf-8.
            string charSet = "";
            if (contentType.find(L"text") != contentType.npos)  //NOXLATE
            {
                charSet = MapAgentStrings::Utf8Text;
            }
            printf(MapAgentStrings::ContentTypeHeader, MG_WCHAR_TO_CHAR(contentType), charSet.c_str());
        }
        else
        {
            printf(MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
        }

        Ptr<MgByteReader> outputReader;
        Ptr<MgDisposable> resultObj = result->GetResultObject();
        MgDisposable* pResultObj = (MgDisposable*)resultObj;

        if (NULL != dynamic_cast<MgByteReader*>(pResultObj))
        {
            outputReader = (MgByteReader*) SAFE_ADDREF(pResultObj);
        }
        else if (NULL != dynamic_cast<MgStringCollection*>(pResultObj))
        {
            outputReader = ((MgStringCollection*)pResultObj)->ToXml();
        }
        else if (NULL != dynamic_cast<MgSpatialContextReader*>(pResultObj))
        {
            outputReader = ((MgSpatialContextReader*)pResultObj)->ToXml();
        }
        else if (NULL != dynamic_cast<MgLongTransactionReader*>(pResultObj))
        {
            outputReader = ((MgLongTransactionReader*)pResultObj)->ToXml();
        }
        else if (NULL != dynamic_cast<MgHttpPrimitiveValue*>(pResultObj))
        {
            stringVal = ((MgHttpPrimitiveValue*)pResultObj)->ToString();
        }

        if (stringVal.length() > 0)
        {
            string utf8 = MG_WCHAR_TO_CHAR(stringVal);
            printf(MapAgentStrings::ContentLengthHeader, utf8.length());
            printf("\r\n%s",utf8.c_str());
        }
        else if (outputReader != NULL)
        {
            Ptr<MgHttpHeader> respHeader = response->GetHeader();
            //Check for chunking hint
            if (respHeader->GetHeaderValue(MgHttpResourceStrings::hrhnTransfer_Encoding) == MgHttpResourceStrings::hrhnChunked)
            {
                CgiReaderStreamer crs(outputReader);
                crs.StreamResult();
            }
            else
            {
                INT64 outLen = outputReader->GetLength();
                printf(MapAgentStrings::ContentLengthHeader,(INT32)outLen);
                printf("\r\n");
                unsigned char buf[4096];
                int nBytes = outputReader->Read(buf,4096);
                while (nBytes > 0)
                {
                    fwrite(buf, 1, nBytes, stdout);
                    nBytes = outputReader->Read(buf,4096);
                }
            }
        }
        else
        {
            printf(MapAgentStrings::ContentLengthHeader, 0);
            printf("\r\n");
        }
    }

    MG_CATCH_AND_THROW(L"CgiResponseHandler.SendResponse");
}