Esempio n. 1
0
    def HandleAddSnippetSetRequest(self, request, response):
        """Handles add snippets set request.

    Args:
      request: request object.
      response: response object.

    Raises:
      SnippetsServeException, psycopg2.Warning/Error.
    """
        logger.debug("HandleAddSnippetSetRequest...")

        snippets_set_name = request.GetIdentifier(constants.SNIPPET_SET_NAME)
        if not snippets_set_name:
            raise exceptions.SnippetsServeException(
                "HandleAddSnippetSetRequest: missing or invalid snippet set name."
            )

        snippets_set = request.GetParameter(constants.SNIPPET_SET)
        if not snippets_set:
            raise exceptions.SnippetsServeException(
                "HandleAddSnippetSetRequest: missing snippet set data.")

        try:
            # Dense snippets tree, since we accept snippets in client friendly form,
            # i.e. sparse tree json.
            dense_snippets = tree_utils.CompactTree(snippets_set, logger)
        except Exception as e:
            raise exceptions.SnippetsServeException(
                "Couldn't parse snippet set: %s. Error: %s" %
                (snippets_set_name, e))

        set_content = json.dumps(dense_snippets)

        if self._SnippetSetExists(snippets_set_name):
            # It's ok if snippets set already exists. It means we edit existing one.
            logger.debug("Update snippets set: %s", snippets_set_name)

            query_string = "UPDATE snippet_set_table SET content = %s WHERE name = %s"
            self._DbModify(query_string, (set_content, snippets_set_name))
        else:
            logger.debug("Add snippets set: %s", snippets_set_name)
            query_string = (
                "INSERT INTO snippet_set_table (name, content) VALUES(%s, %s)")
            self._DbModify(query_string, (snippets_set_name, set_content))

        snippets_set = basic_types.SnippetSet(snippets_set_name,
                                              dense_snippets)
        http_io.ResponseWriter.AddJsonBody(response, constants.STATUS_SUCCESS,
                                           snippets_set)
Esempio n. 2
0
    def HandleDeleteSnippetSetRequest(self, request, response):
        """Handles delete snippets set request.

    Args:
      request: request object.
      response: response object.

    Raises:
      SnippetsServeException, psycopg2.Warning/Error.
    """
        logger.debug("HandleDeleteSnippetSetRequest...")
        snippets_set_name = request.GetParameter(constants.SNIPPET_SET_NAME)
        if not snippets_set_name:
            raise exceptions.SnippetsServeException(
                "HandleDeleteSnippetSetRequest: missing snippets set name.")

        # Check if the snippets set exists. If it doesn't then just return success.
        if not self._SnippetSetExists(snippets_set_name):
            http_io.ResponseWriter.AddJsonBody(response,
                                               constants.STATUS_SUCCESS, None)
            return

        # Delete the snippets set entry.
        query_string = "DELETE FROM snippet_set_table WHERE name = %s"
        self._DbModify(query_string, (snippets_set_name, ))

        http_io.ResponseWriter.AddJsonBody(response, constants.STATUS_SUCCESS,
                                           None)
Esempio n. 3
0
    def __ParsePostInput(self, post_input, request):
        """Parses POST request input.

    Args:
      post_input: POST request input.
      request: request object to collect exptracted parameters.
    Raises:
      SnippetsServeException.
    """
        post_dct = urlparse.parse_qs(post_input)
        cmd = post_dct.get(constants.CMD, [""])[0]
        if not cmd:
            return

        # Extract all the parameters for corrresponding command.
        if cmd == constants.CMD_ADD_SNIPPET_SET:
            logger.debug("%s: %s", constants.CMD, cmd)
            logger.debug("%s: %s", constants.SNIPPET_SET_NAME,
                         post_dct.get(constants.SNIPPET_SET_NAME, [""])[0])
            logger.debug("%s: %s", constants.SNIPPET_SET,
                         post_dct.get(constants.SNIPPET_SET, [""])[0])
            request.SetParameter(
                constants.SNIPPET_SET_NAME,
                post_dct.get(constants.SNIPPET_SET_NAME, [""])[0])
            request.SetParameter(constants.SNIPPET_SET,
                                 post_dct.get(constants.SNIPPET_SET, [""])[0])
        else:
            raise exceptions.SnippetsServeException(
                "Internal Error - Invalid Request Command: %s." % cmd)

        request.SetParameter(constants.CMD, cmd)
  def DoRequest(self, request, response):
    """Handles request by delegating it to manager."""
    assert isinstance(request, http_io.Request)
    assert isinstance(response, http_io.Response)
    # Check for init failure and return an error status and appropriate message.
    if not self._manager:
      http_io.ResponseWriter.AddJsonFailureBody(
          response,
          "Server-side Internal Error: Failure to init SnippetsHandler")
      return

    try:
      cmd = request.GetParameter(constants.CMD)

      if not cmd:
        raise exceptions.StreamPublisherServletException(
            "Internal Error - Missing Request Command.")

      if cmd == constants.CMD_QUERY:
        self._manager.HandleQueryRequest(request, response)
      elif cmd == constants.CMD_PING:
        self._manager.HandlePingRequest(request, response)
      elif cmd == constants.CMD_ADD_SNIPPET_SET:
        self._manager.HandleAddSnippetSetRequest(
            request, response)
      elif cmd == constants.CMD_DELETE_SNIPPET_SET:
        self._manager.HandleDeleteSnippetSetRequest(
            request, response)
      else:
        raise exceptions.SnippetsServeException(
            "Invalid Request Command: {}.".format(cmd))
    except exceptions.SnippetsServeException as e:
      logger.error(e)
      http_io.ResponseWriter.AddJsonFailureBody(response, str(e))
    except (psycopg2.Warning, psycopg2.Error) as e:
      logger.error(e)
      http_io.ResponseWriter.AddJsonFailureBody(
          response,
          "Database error: {}".format(e))
    except Exception as e:
      logger.error(e)
      http_io.ResponseWriter.AddJsonFailureBody(
          response, "Server-side Internal Error: {}".format(e))
Esempio n. 5
0
    def HandleQueryRequest(self, request, response):
        """Handles query requests.

    Args:
      request: request object.
      response: response object
    Raises:
      SnippetsServeException, psycopg2.Error/Warning.
    """
        query_cmd = request.GetParameter(constants.QUERY_CMD)
        if not query_cmd:
            raise exceptions.SnippetsServeException(
                "Internal Error - Missing Query Command.")

        # List all snippets sets registered on the server.
        if query_cmd == constants.QUERY_CMD_LIST_SNIPPET_SETS:
            query_string = "SELECT name, content FROM snippet_set_table"
            results = self._DbQuery(query_string)
            snippets_set_list = [
                self.__BuildSnippetSetObj(row[0], row[1]) for row in results
            ]

            http_io.ResponseWriter.AddJsonBody(response,
                                               constants.STATUS_SUCCESS,
                                               snippets_set_list)
        # Preview details for a specific snippets set.
        elif query_cmd == constants.QUERY_CMD_SNIPPET_SET_DETAILS:
            snippets_set_name = request.GetParameter(
                constants.SNIPPET_SET_NAME)
            if not snippets_set_name:
                raise exceptions.SnippetsServeException(
                    "HandleQueryRequest: missing snippets set name.")

            end_snippet = self.GetSnippetSetDetails(snippets_set_name)
            if not end_snippet:
                raise exceptions.SnippetsServeException(
                    "The snippet set %s does not exist." % snippets_set_name)

            logger.debug("Snippet set name: %s", snippets_set_name)
            logger.debug("End snippet: %s", end_snippet)
            snippets_set = self.__BuildSnippetSetObj(snippets_set_name,
                                                     end_snippet)
            http_io.ResponseWriter.AddJsonBody(response,
                                               constants.STATUS_SUCCESS,
                                               snippets_set)
        # List paths of metafields available for editing.
        elif query_cmd == constants.QUERY_CMD_LIST_META_FIELD_PATHS:
            meta_fields_obj = json.loads(metainfo_by_fieldpath.META_INFO)
            field_paths_list = meta_fields_obj.keys()
            field_paths_json = json.dumps(field_paths_list,
                                          indent=2,
                                          separators=(",", ":"))
            logger.debug("Meta field paths: %s", field_paths_json)

            http_io.ResponseWriter.AddJsonBody(response,
                                               constants.STATUS_SUCCESS,
                                               field_paths_json)
        # List metafields available for editing.
        elif query_cmd == constants.QUERY_CMD_META_FIELDS_SET:
            meta_fields_obj = json.loads(metainfo_by_fieldpath.META_INFO)
            meta_fields_json = json.dumps(meta_fields_obj,
                                          indent=2,
                                          separators=(",", ":"))
            logger.debug("Meta fields: %s", meta_fields_json)
            http_io.ResponseWriter.AddJsonBody(response,
                                               constants.STATUS_SUCCESS,
                                               meta_fields_json)
        else:
            raise exceptions.SnippetsServeException(
                "Invalid Query Command: %s." % query_cmd)