def run(self, service, inputTable, queryMeta): with base.getTableConn() as conn: ssaTable = rsc.TableForDef(self.queriedTable, connection=conn) try: # XXX TODO: Figure out why the unquote here is required. accref = urllib.unquote(inputTable.getParam("accref")) res = list( ssaTable.iterQuery(ssaTable.tableDef, "accref=%(accref)s", {"accref": accref})) if not res: raise svcs.UnknownURI( "No spectrum with accref %s known here" % inputTable.getParam("accref")) ssaRow = res[0] finally: ssaTable.close() resData = makeSDMDataForSSARow(ssaRow, self.sdmDD) votContextArgs = {} if queryMeta["tdEnc"]: votContextArgs["tablecoding"] = "td" # This is for VOSpec, in particular the tablecoding; I guess once # we actually support the sed DM, this should go, and the # specview links should use sed dcc sourcePaths. if inputTable.getParam("dm") == "sed": hackSDMToSED(resData) votContextArgs["tablecoding"] = "td" return (base.votableType, votable.asString(makeSDMVOT(resData, **votContextArgs)))
def renderHTTP(self, ctx): if not hasattr(self, "table"): # _retrieveTableDef did not run, i.e., no tableName was given raise svcs.UnknownURI( "You must provide a table name to this renderer.") self.metaCarrier = self.table return super(TableInfoRenderer, self).renderHTTP(ctx)
def _retrieveTableDef(self, tableName): try: self.tableName = tableName self.table = registry.getTableDef(tableName) self.describingRD = self.table.rd except base.NotFoundError, msg: raise base.ui.logOldExc(svcs.UnknownURI(str(msg)))
def _retrieveNote(self, tableName, noteTag): try: table = registry.getTableDef(tableName) self.metaCarrier = table self.noteHTML = table.getNote(noteTag).getContent( targetFormat="html", macroPackage=table) except base.NotFoundError, msg: raise base.ui.logOldExc(svcs.UnknownURI(msg))
def __init__(self, ctx, service): grend.ServiceBasedPage.__init__(self, ctx, service) self.customTemplate = None try: self.customTemplate = self.service.getTemplate("fixed") except KeyError: raise base.ui.logOldExc( svcs.UnknownURI("fixed renderer needs a 'fixed' template"))
def renderHTTP(self, ctx): if not self.queryValue: raise svcs.UnknownURI( "This page is a root page for a" " query-based service. You have to give a valid value in the" " path.") data = {self.service.getProperty("queryField"): self.queryValue} return self.runServiceWithFormalData(data, ctx).addCallback( self._formatOutput, ctx).addErrback(self._handleError, ctx)
def renderHTTP(self, ctx): # look for a matching publication in the parent service... for pub in self.service.publications: if pub.render == self.name: break else: # no publication, 404 raise svcs.UnknownURI( "No publication for an external service here.") raise svcs.WebRedirect( base.getMetaText(pub, "accessURL", macroPackage=self.service))
def _parseAccessPath(self): # The scheme is manually handled to shoehorn urlparse into supporting # queries (and, potentially, fragments) ap = self.pr["accessPath"] if not ap.startswith("dcc:"): raise svcs.UnknownURI("DCC products can only be generated for dcc" " URIs") res = urlparse.urlparse(ap[4:]) self.core = base.caches.getRD(res.netloc.replace(".", "/")).getById( res.path.lstrip("/")) self.accref = res.query
def locateChild(self, ctx, segments): # By default, ServiceBasedPages have no directory-like resources. # So, if some overzealous entity added a slash, just redirect. # Do not upcall to this if you override locateChild. if segments == ("", ): raise svcs.WebRedirect(url.URL.fromContext(ctx)) else: res = ResourceBasedPage.locateChild(self, ctx, segments) if res[0] is None: raise svcs.UnknownURI("%s has no child resources" % repr(self.name)) return res
def locateChild(self, ctx, segments): relPath = "/".join(segments) path = self.userPath + relPath if os.path.exists(path): return StaticFile(path, base.caches.getRD(registry.SERVICELIST_ID)), () path = self.systemPath + relPath if os.path.exists(path): return StaticFile(path, base.caches.getRD(registry.SERVICELIST_ID)), () raise svcs.UnknownURI("No matching file," " neither built-in nor user-provided")
def locateChild(self, ctx, segments): request = inevow.IRequest(ctx) uwsactions.lowercaseProtocolArgs(request.args) if not segments[-1]: # trailing slashes are forbidden here if len(segments ) == 1: # root resource; don't redirect, it would be a loop return self, () raise svcs.WebRedirect( self.service.getURL("tap") + "/" + "/".join(segments[:-1])) try: self.gatherUploadFiles(request) if (getTAPVersion() != utils.getfirst(request.args, "version", getTAPVersion())): return uwsactions.ErrorResource({ "msg": "Version mismatch; this service only supports" " TAP version %s." % getTAPVersion(), "type": "ValueError", "hint": "" }), () if segments: if segments[0] == 'sync': res = getSyncResource(ctx, self.service, segments[1:]) elif segments[0] == 'async': res = asyncrender.getAsyncResource(ctx, tap.WORKER_SYSTEM, "tap", self.service, segments[1:]) elif segments[0] == 'availability': res = vosi.VOSIAvailabilityRenderer(ctx, self.service) elif segments[0] == 'capabilities': res = vosi.VOSICapabilityRenderer(ctx, self.service) elif segments[0] == 'tables': res = vosi.VOSITablesetRenderer(ctx, self.service) elif segments[0] == 'examples': from gavo.web import examplesrender res = examplesrender.Examples(ctx, self.service) else: raise svcs.UnknownURI("Bad TAP path %s" % "/".join(segments)) return res, () except svcs.UnknownURI: raise except base.Error, ex: # see flagError in protocols.uws for the reason for the next if if not isinstance(ex, (base.ValidationError, uws.JobNotFound)): base.ui.notifyError("TAP error") return uwsactions.ErrorResource(ex), ()
def _formatOutput(self, res, ctx): # XXX TODO: We need a sensible common output framework, and quick. # Then do away with the quick VOTable hack if res.queryMeta["format"] == "VOTable": return VOTableResource(res) nMatched = res.queryMeta.get("Matched", 0) if nMatched == 0: raise svcs.UnknownURI("No record matching %s." % (self.queryValue)) elif nMatched == 1: self.customTemplate = self.getTemplate("resultline") else: self.customTemplate = self.getTemplate("resulttable") self.result = res return defer.maybeDeferred(super(QPRenderer, self).renderHTTP, ctx).addErrback(self._handleError, ctx)
def getSyncResource(ctx, service, segments): if segments: raise svcs.UnknownURI("No resources below sync") request = common.getfirst(ctx, "request", base.Undefined) if request == "doQuery": return TAPQueryResource(service, ctx) elif request == "getCapabilities": return vosi.VOSICapabilityRenderer(ctx, service) return uwsactions.ErrorResource({ "type": "ParameterError", "msg": "Invalid REQUEST: '%s'" % request, "hint": "Only doQuery and getCapabilities supported here" })
def locateChild(self, ctx, segments): rdId = "/".join(segments) try: self.clientRD = base.caches.getRD(rdId) if hasattr(self.clientRD, "getRealRD"): self.clientRD = self.clientRD.getRealRD() self.metaCarrier = self.clientRD self.macroPackage = self.clientRD except base.RDNotFound: raise base.ui.logOldExc( svcs.UnknownURI("No such resource descriptor: %s" % rdId)) except Exception: # RD is botched. Clear cache and give an error base.caches.clearForName(rdId) self._extractDamageInfo() return self, ()
def renderHTTP(self, ctx): request = inevow.IRequest(ctx) try: data = { "accref": products.RAccref.fromRequest(self.pathFromSegments, request) } except base.NotFoundError: raise base.ui.logOldExc(svcs.UnknownURI("No product specified")) # deferring here and going to all the trouble of running a core # is probably overkill; currently, the main thing that'd require # handwork is figuring out authentication in parallel with what # needs to be done for tar files. We should do better, indded. return self.runServiceWithFormalData(data, ctx).addCallback( self._deliver, ctx)
def locateChild(self, ctx, segments): from gavo.registry import builders rdParts, svcId = segments[:-1], segments[-1] rdId = "/".join(rdParts) try: resob = base.caches.getRD(rdId).getById(svcId) except base.NotFoundError: raise svcs.UnknownURI( "The resource %s#%s is unknown at this site." % (rdId, svcId)) return common.TypedData( utils.xmlrender( OAI.PMH[ OAI.responseDate[datetime.datetime.utcnow().isoformat()], OAI.metadata[builders.getVORMetadataElement(resob)]], prolog="<?xml version='1.0'?>" "<?xml-stylesheet href='/static/xsl/oai.xsl' type='text/xsl'?>", ), "application/xml"), ()
def locateChild(self, ctx, segments): if len(segments) == 1 and not segments[0]: return self, () if self.staticPath is None: raise svcs.ForbiddenURI("No static data on this service") relPath = "/".join(segments) destName = os.path.join(self.staticPath, relPath) if os.path.isdir(destName): if not destName.endswith("/"): raise svcs.WebRedirect(inevow.IRequest(ctx).uri + "/") return static.File(destName).directoryListing(), () elif os.path.isfile(destName): return ifpages.StaticFile(destName, self.rd), () else: raise svcs.UnknownURI("No %s available here." % relPath)
def makeSDMDataForPUBDID(pubDID, ssaTD, spectrumData, sdmVersion=base.getConfig("ivoa", "sdmVersion")): """returns a rsc.Data instance containing an SDM compliant spectrum for pubDID from ssaTable. ssaTD is the definition of a table containg the SSA metadata, spectrumData is a data element making a primary table containing the spectrum data from an SSA row (typically, this is going to be the tablesource property of an SSA service). """ with base.getTableConn() as conn: ssaTable = rsc.TableForDef(ssaTD, connection=conn) matchingRows = list( ssaTable.iterQuery(ssaTable.tableDef, "ssa_pubdid=%(pubdid)s", {"pubdid": pubDID})) if not matchingRows: raise svcs.UnknownURI("No spectrum with pubdid %s known here" % pubDID) return makeSDMDataForSSARow(matchingRows[0], spectrumData, sdmVersion=sdmVersion)
def renderHTTP(self, ctx): raise svcs.UnknownURI(self.rAccref.accref)
def renderHTTP(self, ctx): raise svcs.UnknownURI("What resource record do you want?")
def __init__(self, ctx, service): grend.ServiceBasedPage.__init__(self, ctx, service) if not service.customPage: raise svcs.UnknownURI("No custom page defined for this service.") pageClass, self.reloadInfo = service.customPageCode self.realPage = pageClass(ctx, service)
def renderHTTP(self, ctx): raise svcs.UnknownURI("What did you expect here?")
def _handleError(self, failure, ctx): # all errors are translated to 404s failure.printTraceback() raise svcs.UnknownURI("The query initiated by your URL failed," " yielding a message '%s'." % failure.getErrorMessage())
def renderHTTP_notFound(self, ctx): try: raise svcs.UnknownURI("locateChild returned None") except svcs.UnknownURI: return NotFoundPage(failure.Failure())
def renderHTTP(self, ctx): if not hasattr(self, "noteTag"): # _retrieveTableDef did not run, i.e., no tableName was given raise svcs.UnknownURI( "You must provide table name and note tag to this renderer.") return super(TableNoteRenderer, self).renderHTTP(ctx)