Exemplo n.º 1
0
    def render_PUT(self, request):

        #take parameters. In this case, the content for update the file
        args = http.parse_qs(request.content.read(), 1)
        if not args:
            return resource.ErrorPage(400, "INCORRECT PARAMETERS", "Supervise parameters, you not put anything to update ").render(request)

        try:
            _, file_resource, file_id, _ = split_path(request.path, 4, 4, True)
        except:
            return resource.ErrorPage(400, "INCORRECT PARAMETERS", "Supervise parameters, the correct form is api/file/file_id/data ").render(request)
    
        # We look up the name of file, and full path, to update it.
        message = api_library.get_metadata(1234, file_id)
        if not message:
            return resource.ErrorPage(404, "NOT FOUND", "File or folder not found at the specified path:" + request.path).render(request)
        message = json.loads(message)
        # Create new version to save old content version
        #TODO: Define mimetype, size and chunk
        message_new_version = api_library.update_data(1234, message["id"], message["parent"], None, None, None)
        if not message_new_version:
            return resource.ErrorPage(404, "NOT FOUND", "Some problem to create a new version of file").render(request)

        # TODO: Using name and full path update the file into DB, using new version.
  
        request.setHeader("content-type", "application/json")
        request.finish()
        return server.NOT_DONE_YET
Exemplo n.º 2
0
    def render(self, resrc):
        """
        Ask a resource to render itself.

        @param resrc: a L{twisted.web.resource.IResource}.
        """
        try:
            body = resrc.render(self)
        except UnsupportedMethod, e:
            allowedMethods = e.allowedMethods
            if (self.method == "HEAD") and ("GET" in allowedMethods):
                # We must support HEAD (RFC 2616, 5.1.1).  If the
                # resource doesn't, fake it by giving the resource
                # a 'GET' request and then return only the headers,
                # not the body.
                log.msg("Using GET to fake a HEAD request for %s" %
                        (resrc,))
                self.method = "GET"
                self._inFakeHead = True
                body = resrc.render(self)

                if body is NOT_DONE_YET:
                    log.msg("Tried to fake a HEAD request for %s, but "
                            "it got away from me." % resrc)
                    # Oh well, I guess we won't include the content length.
                else:
                    self.setHeader('content-length', str(len(body)))

                self._inFakeHead = False
                self.method = "HEAD"
                self.write('')
                self.finish()
                return

            if self.method in (supportedMethods):
                # We MUST include an Allow header
                # (RFC 2616, 10.4.6 and 14.7)
                self.setHeader('Allow', ', '.join(allowedMethods))
                s = ('''Your browser approached me (at %(URI)s) with'''
                     ''' the method "%(method)s".  I only allow'''
                     ''' the method%(plural)s %(allowed)s here.''' % {
                    'URI': escape(self.uri),
                    'method': self.method,
                    'plural': ((len(allowedMethods) > 1) and 's') or '',
                    'allowed': string.join(allowedMethods, ', ')
                    })
                epage = resource.ErrorPage(http.NOT_ALLOWED,
                                           "Method Not Allowed", s)
                body = epage.render(self)
            else:
                epage = resource.ErrorPage(
                    http.NOT_IMPLEMENTED, "Huh?",
                    "I don't know how to treat a %s request." %
                    (escape(self.method),))
                body = epage.render(self)
Exemplo n.º 3
0
	def render(self, resrc):
		"""
		Ask a resource to render itself.

		@param resrc: a L{twisted.web.resource.IResource}.
		"""
		try:
			body = resrc.render(self)
		except UnsupportedMethod, e:
			sAllowedMethodList = e.allowedMethods
			if (self.method == "HEAD") and ("GET" in sAllowedMethodList):
				# We must support HEAD (RFC 2616, 5.1.1).  If the
				# resource doesn't, fake it by giving the resource
				# a 'GET' request and then return only the headers,
				# not the body.
				log.Info("Using GET to fake a HEAD request for %s" % resrc)
				self.method = "GET"         #来自http.Request
				self._inFakeHead = True     #来自web.server.Request
				body = resrc.render(self)

				if body is NOT_DONE_YET:
					log.Info("Tried to fake a HEAD request for %s, but it got away from me." % resrc)
					# Oh well, I guess we won't include the content length.
				else:
					self.setHeader("content-length", str(len(body)))

				self._inFakeHead = False
				self.method = "HEAD"
				self.write("")
				self.finish()
				return

			if self.method in SUPPORT_METHOD_LIST:
				# We MUST include an Allow header
				# (RFC 2616, 10.4.6 and 14.7)
				self.setHeader('Allow', ', '.join(sAllowedMethodList))
				s = ("""Your browser approached me (at %(URI)s) with"""
					 """ the method "%(method)s".  I only allow"""
					 """ the method%(plural)s %(allowed)s here.""" % {
					"URI" : escape(self.uri),
					"method" : self.method,
					"plural" : ((len(sAllowedMethodList) > 1) and "s") or "",
					"allowed" : string.join(sAllowedMethodList, ", ")
					})
				epage = resource.ErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s)
				body = epage.render(self)
			else:
				epage = resource.ErrorPage(
					http.NOT_IMPLEMENTED, "Huh?",
					"I don't know how to treat a %s request." %
					(escape(self.method),))
				body = epage.render(self)
Exemplo n.º 4
0
    def render_DELETE(self, request):

        try:    
            _, _, folder_id = split_path(request.path, 3, 3, True)
        except:
            return resource.ErrorPage(400, "INCORRECT PARAMETERS", "It's mandatory to enter a folder_id. ").render(request)
        
        message = api_library.delete_item(123, folder_id)
        if not message:
            return resource.ErrorPage(404, "NOT FOUND", "File or folder not found at the specified path:" + request.path).render(request)
        request.setHeader("content-type", "application/json")
        request.write(message)
        request.finish()
        return server.NOT_DONE_YET
Exemplo n.º 5
0
 def getChild(self, path, request):
     if path == "events":
         # Server-Sent Events use a GET with a use-once URL, not a token
         return self.event_dispatcher
     # everything else requires a token, check it here
     payload = json.loads(request.content.read())
     if not equal(payload["token"], self.access_token):
         return resource.ErrorPage(http.UNAUTHORIZED, "bad token",
                                   "Invalid token")
     rclass = handlers.get(path)
     if not rclass:
         return resource.ErrorPage(http.NOT_FOUND, "unknown method",
                                   "Unknown method")
     r = rclass(self.db, self.agent, self.event_dispatcher, payload)
     return r
Exemplo n.º 6
0
 def getChild(self, name, txrequest):
     target = self.get_target()
     try:
         newtarget = getattr(target, to_native_str(name))
         return ControlResource(self.crawler, newtarget)
     except AttributeError:
         return resource.ErrorPage(404, "No Such Resource", "No such child resource.")
Exemplo n.º 7
0
    def render_POST(self, request):
        def started(result):
            request.finish()

        def stopped(result):
            request.finish()

        data = json.loads(request.content.getvalue())
        action = data.get("action", None)

        s = supervisor.get()

        if action is None:
            return resource.ErrorPage(http.BAD_REQUEST,
                                      http.RESPONSES[http.BAD_REQUEST],
                                      "action required")

        elif action.lower() == "start":
            d = s.startMinecraft(jar=settings.config["minecraft"]["jar"],
                                 path=settings.config["minecraft"]["home"])
            d.addCallback(started)

        elif action.lower() == "stop":
            d = s.stopMinecraft()
            d.addCallback(stopped)

        return server.NOT_DONE_YET
Exemplo n.º 8
0
 def getChild(self, name, request):
     target = self.get_target()
     try:
         newtarget = getattr(target, name)
         return JsonRpcResource(self.crawler, newtarget)
     except AttributeError:
         return resource.ErrorPage(404, "No Such Resource", "No such child resource.")
Exemplo n.º 9
0
    def processEnded(self, reason):
        if reason.value.exitCode != 0:
            self._log.error(
                "CGI {uri} exited with exit code {exitCode}",
                uri=self.request.uri,
                exitCode=reason.value.exitCode,
            )
        if self.errortext:
            self._log.error(
                "Errors from CGI {uri}: {errorText}",
                uri=self.request.uri,
                errorText=self.errortext,
            )

        if self.handling_headers:
            self._log.error(
                "Premature end of headers in {uri}: {headerText}",
                uri=self.request.uri,
                headerText=self.headertext,
            )
            if not self._requestFinished:
                self.request.write(
                    resource.ErrorPage(
                        http.INTERNAL_SERVER_ERROR,
                        "CGI Script Error",
                        "Premature end of script headers.",
                    ).render(self.request))

        if not self._requestFinished:
            self.request.unregisterProducer()
            self.request.finish()
Exemplo n.º 10
0
    def handle_request(self, request):
        try:
            username = request.args['user'][0]
            cxn = yield txmongo.MongoConnection()
            # Don't yield the user query
            user_defer = cxn.pycon.users.find_one({'name': username})

            # Go ahead with the translation regardless of 
            # whether we find a user.
            input_str = request.args['data'][0]
            from txtranslator import TranslatorClient
            client = TranslatorClient(SVC_HOST, SVC_PORT)
            output_defer = client.translate2(input_str)

            # Wait until we have both results.
            output_str = yield output_defer
            user = yield user_defer

            if user:
                request.write("%s: %s" % (str(user['name']), output_str))
            else:
                request.write("User '%s' not found!" % username)
        except Exception, err:
            print err
            request.write(resource.ErrorPage(500, "Internal Server Error.", err).render(request))
Exemplo n.º 11
0
 def __init__(self, res, realm):
     HTTPRootResource.__init__(self, res)
     self.realm = realm
     self.authorized = False
     self.unauthorizedResource = resource.ErrorPage(
         http.UNAUTHORIZED, "Access denied",
         "Authentication credentials invalid!")
Exemplo n.º 12
0
 def __init__(self, master):
     self.master = master
     master.web = self
     server.Site.__init__(
         self,
         resource.ErrorPage(500, "Internal Server Error",
                            "Web module failed to load"))
Exemplo n.º 13
0
    def render(self, request):
        path = self.path
        if os_path.isfile(path):
            lastComponent = path.split('/')[-1]

            # Set the Header according to what's requested
            if lastComponent in AppTextHeaderFiles:
                request.setHeader('Content-Type', 'application/text')
            elif lastComponent in TextHtmlHeaderFiles or (
                    path.endswith(".html.xml")
                    and lastComponent != "updates.html.xml"):
                request.setHeader('Content-Type', 'text/html; charset=UTF-8')
            elif lastComponent in TextJavascriptHeaderFiles:
                request.setHeader('Content-Type',
                                  'text/javascript; charset=UTF-8')
            elif lastComponent not in NoExplicitHeaderFiles:
                request.setHeader('Content-Type',
                                  'application/xhtml+xml; charset=UTF-8')
            # now go and write the Output
            # request.finish() is called inside webif.py (requestFinish() which is called via renderPage())
            webif.renderPage(request, path, self.session)  # login?
            request.setResponseCode(http.OK)

        elif os_path.isdir(path) and self.addSlash is True:
            uri = "%s/" % (request.path)
            request.redirect(uri)
            return ""

        else:
            return resource.ErrorPage(
                http.NOT_FOUND, "Error 404 - Page not found",
                "The requested resource is not available").render(request)

        return server.NOT_DONE_YET
Exemplo n.º 14
0
    def _get_renderer(self, fmt):
        """
        Get the renderer for the indicated format.

        :param str fmt: The format.  If a method with a prefix of ``render_``
            and a suffix of this format (upper-cased) is found, it will be
            used.

        :return: A callable which takes a twisted.web Request and renders a
            response.
        """
        renderer = None

        if fmt is not None:
            try:
                renderer = getattr(self, "render_{}".format(fmt.upper()))
            except AttributeError:
                return resource.ErrorPage(
                    http.BAD_REQUEST,
                    "Bad Format",
                    "Unknown {} value: {!r}".format(self.formatArgument, fmt),
                ).render

        if renderer is None:
            renderer = self.render_HTML

        return renderer
Exemplo n.º 15
0
 def g(self, request):
     try:
         return f(self, request)
     except Exception as e:
         description, status = humanize_exception(e)
         return resource.ErrorPage(status, "Error",
                                   description).render(request)
Exemplo n.º 16
0
 def __init__(self, res):
     print "[HTTPRootResource}.__init__"
     resource.Resource.__init__(self)
     self.resource = res
     self.sessionInvalidResource = resource.ErrorPage(
         http.PRECONDITION_FAILED, "Precondition failed!",
         "sessionid is missing, invalid or expired!")
     self._sessions = {}
Exemplo n.º 17
0
 def unauthorizedPage(self):
     """
     Page to render when there is no valid token.
     This makes use of L{TokenResource.unauthorizedMessage} by default.
     """
     return resource.ErrorPage(
         UNAUTHORIZED, "Unauthorized", self.unauthorizedMessage()
     )
Exemplo n.º 18
0
 def getChild(self, esid, request):
     try:
         # esid tokens are single-use
         self.unclaimed_event_channels.remove(esid)  # can raise KeyError
         return self.event_channels[esid]
     except KeyError:
         return resource.ErrorPage(http.UNAUTHORIZED, "bad esid",
                                   "Invalid esid")
Exemplo n.º 19
0
    def render_GET(self, request):

        try:
            _, file_resource, file_id, resource, version, _ = split_path(request.path, 4, 6, True)
        except:
            return resource.ErrorPage(400, "INCORRECT PARAMETERS", "Supervise parameters, something is wrong").render(request)

        metadata = api_library.get_metadata(1234, file_id, include_chunks=True, specific_version=version)  
        if not metadata:
                return resource.ErrorPage(404, "NOT FOUND", "File or folder not found at the specified path:" + request.path).render(request)

        # TODO: using metadata, where we can find the name and path of file, return content of file with DB
        content = 'There are the content of specific version of file'
        request.setHeader("content-type", "application/json")
        request.setHeader("content-length", len(content))
        request.write(content)
        request.finish()
        return server.NOT_DONE_YET
Exemplo n.º 20
0
 def render_GET(self, request):
     try:
         request.setResponseCode(200)
         request.setHeader(b'content-type', b'text/plain')
         content = 'I am stat\n'
         return content.encode('ascii')
     except Exception as e:
         return resource.ErrorPage(500, 'Error',
                                   'Message: {}'.format(e)).render(request)
Exemplo n.º 21
0
 def _eb_getFileAlias(self, failure):
     err = failure.trap(NotFound, DisconnectionError)
     if err == DisconnectionError:
         return resource.ErrorPage(
             503, 'Database unavailable',
             'A required database is unavailable.\n'
             'See https://twitter.com/launchpadstatus '
             'for maintenance and outage notifications.')
     else:
         return fourOhFour
Exemplo n.º 22
0
    def getChildWithDefault(self, name, request):
        """
        This should never be called; it's simply required to implement the
        :py:class:`twisted.web.resource.IResource` interface. Just returns
        a 404.

        See: :py:meth:`twisted.web.resource.IResource.getChildWithDefault`
        """
        return resource.ErrorPage(NOT_FOUND, "No Such Resource",
                                  "No Such Resource")
Exemplo n.º 23
0
 def failed(self, failure):
     #XXX: Argh. FIXME.
     failure = str(failure)
     self.request.write(
         resource.ErrorPage(
             http.INTERNAL_SERVER_ERROR, "Server Connection Lost",
             "Connection to distributed server lost:" +
             util._PRE(failure)).render(self.request))
     self.request.finish()
     self._log.info(failure)
Exemplo n.º 24
0
class HTTPNoListingFileService(static.File):
    """Similar to twisted.web.static.File except that instead of listing the
    content of directories, it returns a 403 Forbidden.
    
    """
    _FORBIDDEN_RESOURCE = resource.ErrorPage(
        http.FORBIDDEN, 'Forbidden', 'Directory listing not permitted.')
    _NOT_ALLOWED_RESOURCE = resource.ErrorPage(http.NOT_ALLOWED,
                                               'Method Not Allowed',
                                               'Method not allowed.')

    def directoryListing(self):
        return self._FORBIDDEN_RESOURCE

    def getChild(self, path, request):
        if request.method != 'GET':
            return self._NOT_ALLOWED_RESOURCE
        else:
            return static.File.getChild(self, path, request)
Exemplo n.º 25
0
    def render_GET(self, request):

        args = clear_args(request.args)
        try:
            include_deleted = args.get('include_deleted')
        except:
            include_deleted = False
        try:    
            _, _, folder_id, _ = split_path(request.path, 4, 4, True)
        except:
            return resource.ErrorPage(400, "INCORRECT PARAMETERS", "No tindrie que entra mai aqui ").render(request)
        
        message = api_library.get_folder_contents(123, folder_id, include_deleted)
        if not message:
            return resource.ErrorPage(404, "NOT FOUND", "File or folder not found at the specified path:" + request.path).render(request)
        request.setHeader("content-type", "application/json")
        request.write(message)
        request.finish()
        return server.NOT_DONE_YET
Exemplo n.º 26
0
    def render(self, request):
        if request.getClientIP() == "127.0.0.1":
            return self.resource.render(request)

        if self.login(request.getUser(), request.getPassword()) == False:
            request.setHeader('WWW-authenticate',
                              'Basic realm="%s"' % ("OpenWebif"))
            errpage = resource.ErrorPage(http.UNAUTHORIZED, "Unauthorized",
                                         "401 Authentication required")
            return errpage.render(request)
        else:
            return self.resource.render(request)
Exemplo n.º 27
0
def ResourceTemplate(path, registry):
    from quixote import ptl_compile

    glob = {'__file__': _coerceToFilesystemEncoding("", path),
            'resource': resource.ErrorPage(500, "Whoops! Internal Error",
                                           rpyNoResource),
            'registry': registry}

    e = ptl_compile.compile_template(open(path), path)
    code = compile(e, "<source>", "exec")
    eval(code, glob, glob)
    return glob['resource']
Exemplo n.º 28
0
    def render_POST(self, request):
        self.number_requests += 1
        try:
            data_str = cgi.escape(request.content.read())
            logger.debug('post request data string: "{}"'.format(data_str))
            data_dict = json.loads(data_str)
        except ValueError as e:
            return resource.ErrorPage(
                400, 'BAD_REQUEST',
                'Message: invalid json document').render(request)

        try:
            jsonschema.validate(data_dict, self.schema)
        except jsonschema.ValidationError as e:
            return resource.ErrorPage(
                400, 'BAD_REQUEST',
                'Message: invalid json document').render(request)

        try:
            num_notif = 0
            for notif in data_dict:
                self.queue.put(notif)
                num_notif += 1
            request.setResponseCode(202)
            request.setHeader(b'content-type', b'application/json')
            result = {
                'msg_accepted': num_notif,
                'queue_pending': self.queue.size(),
                'total_requests': self.number_requests
            }
            content = json.dumps(result,
                                 ensure_ascii=True,
                                 indent=4,
                                 separators=(',', ': '),
                                 sort_keys=True)
            logger.debug('response string: "{}"'.format(content))
            return content.encode('ascii')
        except Exception as e:
            return resource.ErrorPage(500, 'Error',
                                      'Message: {}'.format(e)).render(request)
Exemplo n.º 29
0
    def render_GET(self, request):
        # Check that the 'name' URL param was passed.
        name = request.args.get('name', None)
        if name is None:
            return resource.ErrorPage(400, "Bad Request",
                                      "Missing 'name' param.").render(request)
        name = name[0]

        delay_seconds = 2
        print "Delaying for %s seconds." % delay_seconds
        # Delay requires a callback
        reactor.callLater(delay_seconds, delayed_render, request, name)
        return NOT_DONE_YET
Exemplo n.º 30
0
 def render_GET(self, request):
     try:    
         _, _, file_id, resource, version = split_path(request.path, 4, 5, True)
     except:
         return resource.ErrorPage(400, "INCORRECT PARAMETERS", "en principi no tindrie que passar aixo jaja").render(request)
     # if version alone return all versions metadata
     if not version:
         message = api_library.get_versions(1234, file_id)
         if not message:
             return resource.ErrorPage(404, "NOT FOUND", "File or folder not found at the specified path:" + request.path).render(request)
         request.write(message)
         request.finish()
         return server.NOT_DONE_YET
     # if version/id return information about specific version
     message = api_library.get_metadata(1234, file_id, specific_version=version)
     if not message:
         return resource.ErrorPage(404, "NOT FOUND", "File or folder not found at the specified path:" + request.path).render(request)
     request.write(message)
     request.finish()
     return server.NOT_DONE_YET
     
     '''