def HandleUnpublishRequest(self, request, response):
        """Handles un-publish request.

    Cleans up an entry in target_db_table, updates .htaccess file, unregister
    database for serving in Fdb module (clears corresponding Reader/Unpacker),
    deletes the publish manifest files.

    Args:
      request: request object.
      response: response object.
    Raises:
      psycopg2.Error/Warning, PublishServeException.
    """
        # Get target path parameter.
        target_path = request.GetParameter(constants.TARGET_PATH)
        if not target_path:
            raise exceptions.PublishServeException(
                "HandleUnpublishRequest: Missing target path.")

        assert isinstance(target_path, str)

        norm_target_path = serve_utils.NormalizeTargetPath(target_path)
        if not norm_target_path:
            raise exceptions.PublishServeException(
                "Not valid target path %s (path format is /sub_path1[/sub_path2]."
                % target_path)

        request_url = request.GetParameter(constants.ORIGIN_REQUEST_HOST)
        assert request_url

        try:
            self._publish_helper.HandleUnpublishRequest(norm_target_path)
        except Exception:
            # Unregister FusionDb/Portable for serving in Fdb module.
            self._mod_fdb_serve_handler.UnregisterDatabaseForServing(
                request_url, norm_target_path)
            raise
        else:
            # Unregister FusionDb/Portable for serving in Fdb module.
            self._mod_fdb_serve_handler.UnregisterDatabaseForServing(
                request_url, norm_target_path)
            http_io.ResponseWriter.AddBodyElement(response,
                                                  constants.HDR_STATUS_CODE,
                                                  constants.STATUS_SUCCESS)
    def HandleSwapTargetsRequest(self, request, response):
        """Handles swap targets request.

    Sample request:
    '/geserve/Publish?Cmd=SwapTargets&Host=fusion.host.name&
      TargetPathA=target_path_a&TargetPathB=target_path_b

    Args:
      request: request object.
      response: response object.
    Raises:
      PublishServeException.
    """
        logger.debug("HandleSwapTargetsRequest...")

        # Extract parameters.
        target_path_in_a = request.GetParameter(constants.TARGET_PATH_A)
        target_path_in_b = request.GetParameter(constants.TARGET_PATH_B)
        origin_request_host = request.GetParameter(
            constants.ORIGIN_REQUEST_HOST)

        target_path_a = serve_utils.NormalizeTargetPath(target_path_in_a)
        if not target_path_a:
            raise exceptions.PublishServeException(
                "HandleSwapTargetsRequest: Not a valid target path %s "
                "(path format is /sub_path1[/sub_path2]." % target_path_in_a)

        target_path_b = serve_utils.NormalizeTargetPath(target_path_in_b)
        if not target_path_b:
            raise exceptions.PublishServeException(
                "HandleSwapTargetsRequest: Not a valid target path %s "
                "(path format is /sub_path1[/sub_path2]." % target_path_in_b)

        (target_details_a,
         target_details_b) = self._publish_helper.SwapTargets(
             target_path_a, target_path_b)

        # Unpublish targets.

        # There is no need to handle any errors/exceptions here, as they
        # are handled by the 'UnPublish' service.
        request_u = self._CreateUnpublishRequest(origin_request_host,
                                                 target_path_a)
        response_u = http_io.Response()
        self.HandleUnpublishRequest(request_u, response_u)

        request_u = self._CreateUnpublishRequest(origin_request_host,
                                                 target_path_b)
        response_u = http_io.Response()
        self.HandleUnpublishRequest(request_u, response_u)

        # Publish targets with new db_name.
        request_a = self._CreatePublishRequest(origin_request_host,
                                               target_details_a)
        response_a = http_io.Response()
        self.HandlePublishRequest(request_a, response_a)

        request_b = self._CreatePublishRequest(origin_request_host,
                                               target_details_b)
        response_b = http_io.Response()
        self.HandlePublishRequest(request_b, response_b)

        logger.debug("Targets %s and %s have been successfully swapped.",
                     target_path_a, target_path_b)
        http_io.ResponseWriter.AddBodyElement(response,
                                              constants.HDR_STATUS_CODE,
                                              constants.STATUS_SUCCESS)
    def HandleRepublishRequest(self, request, response):
        """Handles republish database request.

    Sample request:
    '/geserve/Publish?Cmd=RepublishDb&Host=fusion.host.name&
    TargetPath=test&DbName=/gevol/assets/Databases/terrain_alpha_pack_test.kdata
    base/gedb.kda/ver00X/gedb'

    Args:
      request: request object.
      response: response object.
    Raises:
      PublishServeException.
    """

        logger.debug("HandleRepublishRequest...")

        # Extract parameters
        db_name = request.GetParameter(constants.DB_NAME)
        target_path_in = request.GetParameter(constants.TARGET_PATH)
        origin_request_host = request.GetParameter(
            constants.ORIGIN_REQUEST_HOST)
        client_host_name = request.GetParameter(constants.HOST_NAME)

        if not db_name or not target_path_in or not client_host_name:
            raise exceptions.PublishServeException(
                "HandleRepublishRequest:db_name, host_name or target_path "
                "parameters not available in the request: %s, %s, %s.",
                db_name, client_host_name, target_path_in)

        target_path = serve_utils.NormalizeTargetPath(target_path_in)
        if not target_path:
            raise exceptions.PublishServeException(
                "HandleRepublishRequest: Not a valid target path %s "
                "(path format is /sub_path1[/sub_path2]." % target_path_in)

        if self._publish_helper.IsDatabasePushed(client_host_name, db_name):
            target_details = self._publish_helper.GetTargetDetails(target_path)
            if not target_details:
                raise exceptions.PublishServeException(
                    "HandleRepublishRequest: Make sure the target path %s "
                    "exists and is currently published." % target_path)

            if "publishcontext" not in target_details.keys():
                raise exceptions.PublishServeException(
                    "Republish is not supported for targets "
                    "published using GEE version 5.1.2 or earlier.")

            # Check if the databases are comparable, versions of the same database.
            if not self._publish_helper.AreDatabasesComparable(
                    db_name, client_host_name, target_details["dbname"],
                    target_details["fusion_host"]):
                raise exceptions.PublishServeException(
                    "HandleRepublishRequest: Database names do not match for target "
                    "and given database. Target database: %s, %s, Input database: %s, "
                    "%s should only be versions of the same database." %
                    (target_details["fusion_host"], target_details["dbname"],
                     client_host_name, db_name))

            # Check if db_name has POI data.
            # Get database ID from gesearch database.
            value = target_details.get("fusion_host", "")
            search_db_id = self._publish_helper.GetSearchDbId(value, db_name)

            if search_db_id == 0:
                # db_name has no POI data. Do not republish if DB published
                # on target has POISearch enabled.
                if "POISearch" in target_details["publishcontext"].get(
                        "searchdefs"):
                    raise exceptions.PublishServeException(
                        "HandleRepublishRequest: target_path %s has POISearch service "
                        "enabled while the new version of database %s has no POISearch "
                        "data. Republish is disabled." %
                        (target_path, db_name))

            # Replace db name with the new one.
            target_details["dbname"] = db_name

            # Unpublish target.
            request_u = self._CreateUnpublishRequest(origin_request_host,
                                                     target_path)
            response_u = http_io.Response()
            self.HandleUnpublishRequest(request_u, response_u)

            # Publish target with new db_name.
            request_p = self._CreatePublishRequest(origin_request_host,
                                                   target_details)
            response_p = http_io.Response()
            self.HandlePublishRequest(request_p, response_p)

            logger.debug(
                "Database %s has been successfully republished to "
                "target %s.", db_name, target_path)

            http_io.ResponseWriter.AddBodyElement(response,
                                                  constants.HDR_STATUS_CODE,
                                                  constants.STATUS_SUCCESS)
    def __GetPublishParameters(self, request):
        """Gets and verifies all publish request parameters.

    Args:
      request: request object.
    Returns:
      The PublishDef object encapsulating set of the publish parameters.
    """
        publish_def = PublishDef()

        # Get Virtual Host name parameter.
        publish_def.virtual_host_name = request.GetParameter(
            constants.VIRTUAL_HOST_NAME)
        if not publish_def.virtual_host_name:
            raise exceptions.PublishServeException(
                "Missing Virtual Host name.")
        assert isinstance(publish_def.virtual_host_name, str)

        # Get target path
        target_path = request.GetParameter(constants.TARGET_PATH)
        if not target_path:
            raise exceptions.PublishServeException("Missing target path.")
        assert isinstance(target_path, str)

        # Normalize target path.
        publish_def.target_path = serve_utils.NormalizeTargetPath(target_path)
        if not publish_def.target_path:
            raise exceptions.PublishServeException(
                "Not valid target path %s (path format is /sub_path1[/sub_path2])."
                % target_path)

        self.__VerifyTargetPath(publish_def.target_path)
        logger.debug("target path: %s", publish_def.target_path)

        # Check whether target path is already in use.
        if self._publish_helper.IsTargetPathUsed(publish_def.target_path):
            raise exceptions.PublishServeException(
                "Target path %s is already in use. Note that paths are "
                "case insensitve. Input another path or"
                " un-publish database using this path." %
                publish_def.target_path)

        # Get db name parameter.
        publish_def.db_name = request.GetParameter(constants.DB_NAME)
        if not publish_def.db_name:
            raise exceptions.PublishServeException("Missing database name.")
        logger.debug("db_name: %s", publish_def.db_name)
        assert isinstance(publish_def.db_name, str)

        (publish_def.db_name,
         publish_def.db_type) = serve_utils.IdentifyPublishedDb(
             publish_def.db_name)

        if serve_utils.IsFusionDb(publish_def.db_type):
            # Get host name parameter that is part of database ID (host, db_name).
            publish_def.client_host_name = request.GetParameter(
                constants.HOST_NAME)
            if not publish_def.client_host_name:
                raise exceptions.PublishServeException("Missing Hostname.")

            assert isinstance(publish_def.client_host_name, str)
        elif serve_utils.IsPortable(publish_def.db_type):
            # There is no a client hostname for Portable databases.
            publish_def.client_host_name = ""
        else:
            raise exceptions.PublishServeException("Unsupported DB type %s." %
                                                   publish_def.db_type)

        # Get snippets set name parameter.
        publish_def.snippets_set_name = request.GetParameter(
            constants.SNIPPET_SET_NAME)
        logger.debug(
            "Snippets set name: %s ", publish_def.snippet_set_name
            if publish_def.snippets_set_name else "not specified.")

        # Get search definition name parameter.
        publish_def.search_tabs = request.GetMultiPartParameter(
            constants.SEARCH_DEF_NAME)
        if publish_def.search_tabs:
            logger.debug("Search tabs: %s", publish_def.search_tabs)
        else:
            logger.debug("Search tabs are not specified.")

        # Get supplemental search definition name parameter.
        publish_def.sup_search_tabs = request.GetMultiPartParameter(
            constants.SUPPLEMENTAL_SEARCH_DEF_NAME)
        if publish_def.sup_search_tabs:
            logger.debug("Supplemental search tabs: %s",
                         publish_def.sup_search_tabs)
        else:
            logger.debug("Supplemental search tabs are not specified.")

        publish_def.need_search_tab_id = request.GetBoolParameter(
            constants.NEED_SEARCH_TAB_ID)

        publish_def.poi_federated = request.GetBoolParameter(
            constants.POI_FEDERATED)

        publish_def.poi_suggestion = request.GetParameter(
            constants.POI_SUGGESTION)

        publish_def.supplemental_ui_label = request.GetParameter(
            constants.SUPPLEMENTAL_UI_LABEL)

        publish_def.serve_wms = request.GetBoolParameter(constants.SERVE_WMS)

        publish_def.force_copy = request.IsForceCopy()
        return publish_def