Beispiel #1
0
 def branch_id_from_branch_name(db, branch_name):
     # This script only finds current branches that have not been deleted.
     branch_id = None
     try:
         # FIXME: Instead of =, use LIKE %% so we can loosely match?
         rows = db.sql(
             """
         SELECT
            DISTINCT(br.stack_id)
         FROM
            branch AS br
         JOIN
            item_versioned AS br_iv
               USING (system_id)
         WHERE
            br_iv.name = %s
            AND NOT br_iv.deleted
            AND br_iv.valid_until_rid = %s
         """, (
                 branch_name,
                 conf.rid_inf,
             ))
         if not rows:
             raise GWIS_Error('Branch "%s" is not recognized.' %
                              (branch_name, ))
         elif len(rows) != 1:
             raise GWIS_Error('Branch named "%s" not unique.' %
                              (branch_name, ))
         else:
             branch_id = int(rows[0]['stack_id'])
     except psycopg2.ProgrammingError, e:
         #raise GWIS_Error('Unanticipated SQL error: "%s" on branch "%s".'
         #                 % (str(e), branch_name,))
         g.assurt(False)
Beispiel #2
0
    def branch_enforce_permissions(qb, min_access):
        '''
      Check the user's rights to access the branch at the given revision ID.
      Since the user might belong to more than one group, uses min() to get the
      user's greatest level of access.
      '''

        log.verbose(
            'branch_enforce_permissions: br_id: %d / rev: %s / min: %s' % (
                qb.branch_hier[0][0],
                qb.revision,
                min_access,
            ))

        access_level_id = None

        branch_many = Many()

        branch_many.search_by_stack_id(qb.branch_hier[0][0], qb)

        if len(branch_many) > 0:
            g.assurt(len(branch_many) == 1)
            log.verbose('branch_many: %s' % (branch_many, ))
            access_level_id = branch_many[0].access_level_id
            log.verbose('access_level_id: %s' % (access_level_id, ))

        if access_level_id is None:
            raise GWIS_Error('Insufficient privileges or unknown branch.')

        if (min_access is not None) and (min_access < access_level_id):
            raise GWIS_Error('Insufficient privileges or unknown branch.')
Beispiel #3
0
    def __init__(self, req, tgraph, route):
        Problem_Base.__init__(self)
        self.req = req
        self.tgraph = tgraph
        self.route = route

        if not self.route.p3_weight_type:
            # Default to basic shortest length search.
            self.route.p3_weight_type = 'len'

        if self.route.p3_weight_type not in tgraph.weight_types:
            log.error('Unknown edge weight type specified: route: %s' %
                      (route, ))
            raise GWIS_Error('%s: %s. Hint: try one of: %s' % (
                'Unknown edge weight type specified',
                self.route.p3_weight_type,
                ', '.join(tgraph.weight_types),
            ))

        if self.route.p3_weight_type not in tgraph.weights_enabled:
            log.error('Disabled edge weight type specified: route: %s' %
                      (route, ))
            raise GWIS_Error('%s: %s. Hint: try one of: %s' % (
                'Disabled edge weight type specified',
                self.route.p3_weight_type,
                ', '.join(tgraph.weights_enabled),
            ))

        if ((self.route.p3_rating_pump)
                and (self.route.p3_rating_pump not in tgraph.rating_pows)):
            log.error('Unknown Bikeability rating spread: route: %s' %
                      (route, ))
            raise GWIS_Error('%s: %s. Hint: try a rating spread of: %s' % (
                'Unknown Bikeability rating spread',
                self.route.p3_rating_pump,
                ', '.join([str(x) for x in tgraph.rating_pows]),
            ))

        if ((self.route.p3_burden_pump)
                and (self.route.p3_burden_pump not in tgraph.burden_vals)):
            log.error('Unknown travel-to-facility burden: route: %s' %
                      (route, ))
            raise GWIS_Error('%s: %s. Hint: try a facility burden of: %s' % (
                'Unknown travel-to-facility burden',
                self.route.p3_burden_pump,
                ', '.join([str(x) for x in tgraph.burden_vals]),
            ))

        if not self.route.p3_spalgorithm:
            # Default to astar search.
            self.route.p3_spalgorithm = 'as*'
        if self.route.p3_spalgorithm not in tgraph.algorithms:
            log.error('Unknown shortest paths algorithm specified: route: %s' %
                      (route, ))
            raise GWIS_Error('%s: %s. Hint: try one of: %s' % (
                'Unknown shortest paths algorithm specified',
                self.route.p3_spalgorithm,
                ', '.join(tgraph.algorithms),
            ))
Beispiel #4
0
 def from_gml(self, qb, elem):
     attachment.One.from_gml(self, qb, elem)
     # The user is allowed to create a branch that was last merged before
     # Current(), because that's how we roll.
     # FIXME: Validate value_type in xxx
     if self.fresh and (not self.value_type):
         # C.f. item_base.One.from_gml_required
         raise GWIS_Error('Missing mandatory attr: "value_type".')
     elif (self.value_type is not None) and (not self.fresh):
         # C.f. item_base.One.from_gml_required
         raise GWIS_Error('Cannot set "value_type" except on create.')
Beispiel #5
0
 def decode_request_control_request(self):
    '''
    Checks that control_type references a valid access control class type.
    Raises on error; returns silently on success.
    '''
    self.control_type = self.decode_key('control_type')
    if (not self.control_type in Op_Handler.valid_control_types):
       raise GWIS_Error('Invalid access control type: ' + self.control_type)
    self.control_context = self.decode_key('control_context')
    if (not self.control_context in Op_Handler.valid_control_contexts):
       raise GWIS_Error('Invalid access control context: ' 
                        + self.control_context)
Beispiel #6
0
 def from_gml_defn(self, elem, defn, attr_synonyms, req_code, pass_number):
     found_attr = False
     attr_value = None
     for attr_name in attr_synonyms:
         # If required is None or not set, it means we shouldn't expect this
         # attribute. In fact, if it's set, kvetch.
         if req_code is None:
             if pass_number == 1:
                 attr_value = elem.get(attr_name, None)
                 if attr_value is not None:
                     found_attr = True  # A no-op, since we're about to raise...
                     raise GWIS_Error('Illegal input attr: "%s".' %
                                      (attr_name, ))
             # else, pass_number is 2, so we're just checking for missing
             #       mandatory create attrs.
         else:
             # Otherwise, look for the attribute.
             attr_value = elem.get(attr_name, None)
             if pass_number == 1:
                 if attr_value is not None:
                     if defn[One.scol_intype] == bool:
                         attr_value = bool(int(attr_value))
                     else:
                         try:
                             g.assurt(defn[One.scol_intype] is not None)
                             attr_value = defn[One.scol_intype](attr_value)
                         except ValueError:
                             # Is this a programmer error or could malformed XML
                             # cause this? I'm think malformed XML could... so we
                             # should raise an error.
                             raise GWIS_Error(
                                 'Bad Attr Type: attr: %s / value: %s / type: %s'
                                 % (
                                     attr_name,
                                     attr_value,
                                     defn[One.scol_intype],
                                 ))
                     found_attr = True
                 else:
                     # We could leave whatever value is already set, but this
                     # fcn. is destructive (i.e., it's not an update).
                     attr_value = defn[One.scol_dfault]
                 setattr(self, defn[One.scol_pyname], attr_value)
             else:
                 g.assurt(pass_number == 2)
                 # Just see if the attr exists.
                 if attr_value is not None:
                     found_attr = True
             if found_attr:
                 break
     return found_attr
Beispiel #7
0
 def decode_request(self):
    'Validate and decode the incoming request.'
    #import rpdb2
    #rpdb2.start_embedded_debugger('password', fAllowRemote=True)
    command.Op_Handler.decode_request(self)
    # Get the type of access control records to fetch. This is required and 
    # the fcn. throws a GWIS_Error() if the access record type is bogus.
    self.decode_request_control_request()
    # The GrAC commands don't know anything about diffing.
    if isinstance(self.req.revision.rev, revision.Diff):
       raise GWIS_Error('GrAC does not support Diff requests.')
    # Hmmm. Maybe we don't support Updated, either. Just Current or Historic.
    if isinstance(self.req.revision.rev, revision.Updated):
       raise GWIS_Error('GrAC does not support Updated requests.')
Beispiel #8
0
 def decode_request(self):
    command.Op_Handler.decode_request(self)
    try:
       self.route_system_id = int(self.decode_key('route_system_id'))
       self.rating = int(self.decode_key('rating'))
    except Exception, e:
       raise GWIS_Error('route_system_id and/or val not valid int(s).')
    def fetch_n_save(self):

        command.Op_Handler.fetch_n_save(self)

        g.assurt(self.item_stack_id)
        g.assurt(self.item_type_id)
        g.assurt(self.remind_when)

        qb = self.req.as_iqb(addons=False)
        g.assurt(qb.filters == Query_Filters(None))
        items_fetched = item_user_access.Many()
        #qb.filters.include_item_stack = True
        qb.filters.dont_load_feat_attcs = True
        #qb.filters.min_access_level = Access_Level.viewer # default: client
        items_fetched.search_by_stack_id(self.item_stack_id, qb)
        if not items_fetched:
            raise GWIS_Error(
                'Item stack ID not found or permission denied: %d' %
                (self.item_stack_id, ))
        g.assurt(len(items_fetched) == 1)
        item = items_fetched[0]
        log.debug('fetch_n_save: fetched: %s' % (str(item), ))
        g.assurt(not item.fresh)
        g.assurt(not item.valid)

        success = self.req.db.transaction_retryable(self.attempt_save,
                                                    self.req, item)

        if not success:
            log.warning('fetch_n_save: failed')
    def decode_request(self):
        command.Op_Handler.decode_request(self)

        num_actions = 0
        #
        self.action_history_add = self.decode_key('hist_add', None)
        if self.action_history_add is not None:
            self.action_history_add = bool(int(self.action_history_add))
            num_actions += 1
        #
        self.action_history_chg = self.decode_key('hist_chg', None)
        if self.action_history_chg is not None:
            self.action_history_chg = bool(int(self.action_history_chg))
            num_actions += 1
        #
        self.action_squelch_pub = self.decode_key('sqel_pub', None)
        if self.action_squelch_pub is not None:
            self.action_squelch_pub = int(self.action_squelch_pub)
            num_actions += 1
        #
        self.action_squelch_usr = self.decode_key('sqel_usr', None)
        if self.action_squelch_usr is not None:
            self.action_squelch_usr = int(self.action_squelch_usr)
            num_actions += 1

        if num_actions != 1:
            raise GWIS_Error('Expecting one of action_history_add, etc.')

# BUG_FALL_2013: FIXME: This is not used. Is this a CcpV1 hangover?
#        I think this is the 'Clear All' button, right??
#        So we should probably implement this...
        self.use_all_in_history = bool(int(self.decode_key('fbil_hist', 0)))
Beispiel #11
0
   def geocode_metrogis(addr):

      g.assurt(False) # Not used; not updated to CcpV2

      gis_ns = "http://www.metrogis.org/geocode"
      gml_ns = "http://www.opengis.net/gml"
      gis_url = "http://geoserver.state.mn.us/geocoder/geocode_response"
      hits_limit = conf.geocode_hit_limit

      # Have to split so that we can separate the address number.
      split_street = addr.street.split()
      split_street_mod = " ".join(split_street[1:len(split_street)])
      # FIXME: Is there a more efficient way to build this long string?
      url2 = (gis_url
              + "?methodName=GeocodeRequest&Version=1.1&CountryCode=US"
              + "&maximumResponses=" + str(hits_limit)
              + "&CompleteAddressNumber=" + urllib.quote(split_street[0])
              + "&CompleteStreetName=" + urllib.quote(split_street_mod)
              + "&PlaceName=" + urllib.quote(addr.city)
              + "&StateName=" + urllib.quote(addr.state)
              + "&ResponseFormat=XML")

      try:
         resp = misc.urllib2_urlopen_readall(url2)
      except Exception, e:
         log.error('Is this an error? %s / %s' % (str(e), resp_f,))
         raise GWIS_Error('Error finding location')
Beispiel #12
0
    def sql_apply_query_filters(self, qb, where_clause="", conjunction=""):

        g.assurt((not conjunction) or (conjunction == "AND"))

        # 2013.12.23: Moving item_findability-related filtering from route.py,
        #             so every item can use it.
        #
        # MAYBE: Add client support for more than just routes? Maybe, tracks?
        #        Regions? A list of all recently viewed items, of all types?

        if self.sql_enabled_squelch_circuitry():
            if not qb.filters.use_stealth_secret:
                gwis_errs = []  # Ignored, but oh, well.
                # itype is, e.g., Item_Type.ROUTE, or 'route'.
                itype = self.one_class.item_type_id
                if not qb.filters.get_id_count(itype, gwis_errs):
                    where_clause, conjunction = self.sql_apply_squelch_filters(
                        qb, where_clause, conjunction)
                # else, searching by stack_id, so ignore item_findability.
            # else, using stealth_secret, so ignore item_findability.
        elif ((qb.filters.findability_recent)
              or (qb.filters.findability_ignore)):
            raise GWIS_Error('Wrong item type for findability_recent')
        # else, item type doesn't squelch, so don't tune squelch filter.

        return item_stack.Many.sql_apply_query_filters(self, qb, where_clause,
                                                       conjunction)
   def decode_request(self):

      command.Op_Handler.decode_request(self)

      # User cannot revert if banned publicly.
      if self.user_client_ban.is_banned():
         raise GWIS_Warning('Cannot revert revisions while banned')

      # Look for the changenote.
      # MAYBE: Do we ensure this is always set?
      self.changenote = self.req.doc_in.find('metadata/changenote').text

      # Load the GWIS.
      revs_vals = self.decode_key('revs', None)
      if not revs_vals:
         raise GWIS_Error('Missing mandatory param: revs')
      try:
         self.revs = [int(r) for r in revs_vals.split(',')]
      except ValueError:
         raise GWIS_Warning(
            'Cannot revert revisions: param "revs" is not csv integers: %s' 
            % (revs_vals,))
      #self.revs_str = "(%s)" % (','.join([str(rid) for rid in self.revs]),)

      # Anonymous users can only revert one revision at a time.
      # MAYBE: Make this a conf option. Maybe anons can't revert.
      if ((self.req.client.username == conf.anonymous_username)
          and (len(self.revs) > 1)):
         raise GWIS_Warning(
            'Anonymous users cannot revert more than 1 revision.')
Beispiel #14
0
 def decode_ids_compact(self, doc_name, doc_in=None):
     if doc_in is None:
         doc_in = self.req.doc_in
     stack_ids = ''
     if doc_in is not None:
         stack_ids_doc = doc_in.find(doc_name)
         if stack_ids_doc is not None:
             # .tag is the element name, and .text is it's value.
             stack_ids_s = stack_ids_doc.text
             if stack_ids_doc.text:
                 try:
                     stack_ids_i = [
                         int(sid) for sid in stack_ids_s.split(',') if sid
                     ]
                     # NOTE: We don't accept client IDs, only actual IDs.
                     stack_ids_a = [
                         str(sid) for sid in stack_ids_i if sid > 0
                     ]
                 except ValueError:
                     log.warning('decode_ids_compact: not ints: %s' %
                                 (stack_ids_doc.text, ))
                     raise GWIS_Error('Stack ID list not integers.')
                 stack_ids = ", ".join(stack_ids_a)
     log.verbose('decode_ids_compact: doc_name: %s / stack_ids: %s' % (
         doc_name,
         stack_ids,
     ))
     return stack_ids
Beispiel #15
0
 def from_gml_required(elem, attr_name, required=True):
     attr_value = elem.get(attr_name, None)
     if required and (attr_value is None):
         # NOTE: This is just a programmer error, so don't worry about if
         # this msg is useful (i.e., don't bother helping troubleshoot).
         raise GWIS_Error('Missing mandatory attr: "%s".' % (attr_name, ))
     return attr_value
Beispiel #16
0
 def from_gml(self, qb, elem):
     item_user_watching.One.from_gml(self, qb, elem)
     # The user is allowed to create a branch that was last merged before
     # Current(), because that's how we roll.
     if (self.version != 0) and (self.last_merge_rid is not None):
         raise GWIS_Error(
             'The attr last_merge_rid may only be set on create.')
 def __init__(self,
              db,
              username,
              branch_hier,
              rev,
              viewport=None,
              filters=None,
              user_id=None):
     g.assurt(db)
     self.db = db
     g.assurt(isinstance(username, basestring))
     self.username = username
     #
     if user_id:
         self.user_id = user_id
     else:
         if self.username:
             try:
                 self.user_id = User.user_id_from_username(db, username)
             except Exception, e:
                 log.debug('User ID not found for user %s: %s' % (
                     username,
                     str(e),
                 ))
                 raise GWIS_Error('User ID not found for user "%s".' %
                                  (username, ))
         else:
Beispiel #18
0
   def decode_request(self):
      command.Op_Handler.decode_request(self)

      self.qb = self.req.as_iqb()

      self.xml = None
      self.routed_port = None
      self.caller_source = self.decode_key('source') # NOTE: required.
      #
      self.route_stack_id = int(self.decode_key('rt_sid', 0))
      if self.route_stack_id and self.qb.filters.only_system_id:
         raise GWIS_Error('Please try just one of stack ID(s) or system ID.')

      self.compute_landmarks = self.decode_key_bool('add_lmrks')

      # Oopsbroke r30747 13/9/24 to r31652 14/4/25 (live 4/14)- Thanks, user!:
      self.as_gpx = self.decode_key_bool('asgpx')
      self.exp_landmarks_uid = self.decode_key('exp_landmarks_uid', -1)

      # The client sets check_invalid when it wants us to fix a broken route,
      # i.e., if an old byway uses byways that have been edited, recalculate
      # the route. This adds time to what could be a fast checkout of an
      # existing route, so the client can let the user choose if and when
      # to fix broken routes. And not that check_invalid is considered
      # false if asgpx=true.
      self.check_invalid = self.decode_key_bool('checkinvalid')

      # MAYBE: If check_invalid, should we automatically set dont_save=True?
      self.dont_save = self.decode_key_bool('dont_save')

      if (not self.route_stack_id) and (not self.qb.filters.only_system_id):
         # This is a new route request. Compute a new route.
         self.decode_request_prepare_new_route()
Beispiel #19
0
 def save_core_save_file_maybe(self, qb):
     # The client should be trying to upload a file.
     if self.job_act == 'create':
         if ((not self.download_fake) and (not self.resident_download)):
             raise GWIS_Error('Please specify an upload file.')
     # Call the base class to save the uploaded file.
     merge_job.One.save_core_save_file_maybe(self, qb)
Beispiel #20
0
 def walk_general(self, state, walkoptions, is_forward):
     # If Walk_Options had a generic payload for us, we could use it to store
     # a pointer to the Problem object, but it doesn't, so have maintain a
     # static lookup in the Problem class.
     #log.debug('walk_general: walk_ops.soul: %s' % (walkoptions.soul))
     try:
         problem = Payload_Byway.outstanding_problems[walkoptions.soul]
     except KeyError:
         raise GWIS_Error('The Edge cannot find its Problem!')
     try:
         state = self.cost(problem, state, walkoptions, is_forward)
     except Exception, e:
         # NOTE: Some errors -- if they're thrown in the Graphserver C code --
         # can cause your system to stall and it processes all the errors
         # (stall for a few minutes). In VirtualBox, I [lb] "disconnect the
         # cable".  I also hover over a command line, poised to execute my
         # 'killrd2' command, which kills the routed_p2 route finder, if I see
         # any errors in the log trace, because you sometimes have a second
         # between seeing the error and the system freezing. (The freeze
         # might not happen on dev. machines, as I've only got one processor
         # allocated to VirtualBox.)
         # FIXME: I'm not sure that sys.exit() really prevents the system from
         # freezing.
         # NOTE: We can't call GWIS_Error because we're running in the context
         # of the Graphserver C library. Also, I don't think sys.exit() stops
         # the system from freezing, because Graphserver always regains
         # control.
         log.error('Programming Error! "%s" / %s' % (
             str(e),
             traceback.format_exc(),
         ))
         sys.exit()
Beispiel #21
0
   def byway_save(self, unsaved_byway, ref_byway):

      log.verbose('byway_save: %s' % (unsaved_byway,))

      if ref_byway is not None:
         # Copy the reference byway's group item accesses.
         g.assurt((unsaved_byway.stack_id > 0) 
                  or (unsaved_byway.split_from_stack_id > 0))
         try:
            if self.qb_cur.db.integrity_errs_okay:
               log.warning('byway_save: unexpected integrity_errs_okay')
            self.qb_cur.db.integrity_errs_okay = True
            unsaved_byway.prepare_and_save_item(self.qb_cur,
               target_groups=None,
               rid_new=self.qb_cur.item_mgr.rid_new,
               ref_item=ref_byway)
         except psycopg2.IntegrityError, e:
            import pdb;pdb.set_trace()
            raise GWIS_Error('%s %s %s'
               % ('Byway already exists!',
                  'The trunky split-from byway has already been leafified: %s'
                     % unsaved_byway,
                  'Have you already imported this Shapefile?: %s'
                     % self.outp_datasrc.GetLayer(0).GetName(),))
         finally:
Beispiel #22
0
 def save_core(self, qb):
     item_user_watching.One.save_core(self, qb)
     # A branch's stack ID always the same as its branch ID (self-referential)
     g.assurt(
         self.stack_id == self.branch_id)  # see save_core_get_branch_id
     # NOTE: We only honor create-branch and delete from local requests. From
     #       flashclient, we just support renaming.
     g.assurt(((self.version > 1) and not self.deleted)
              or qb.request_is_local)
     # NOTE: We've already verified the parent ID is valid. If the item is
     # fresh, we've checked that the user has permissions to make a copy of
     # the parent. If not, we've checked the user can edit the branch.
     if self.fresh:
         self.parent_id = qb.branch_hier[0][0]
     else:
         g.assurt((not self.parent_id)
                  or (self.parent_id == qb.branch_hier[1][0]))
     # The user is allowed to set self.last_merge_rid only once: when the
     # branch is created. Once the branch exists, the user can only change
     # last_merge_rid by performing an update.
     # 2013.04.04: And remember to use rid_new and not rid_max.
     if self.last_merge_rid is None:
         self.last_merge_rid = qb.item_mgr.rid_new
     else:
         # NO: Allow update: g.assurt(self.fresh and (self.version == 1))
         if ((self.last_merge_rid < 0)
                 or (self.last_merge_rid > qb.item_mgr.rid_new)):
             raise GWIS_Error('last_merge_rid out-of-bounds: %d' %
                              (self.last_merge_rid, ))
     # We fetch coverage_area as SVG (which is what all the append_* fcns.
     # expect), but PostGIS has no SVG import function (weird, [lb] thinks).
     # 2014.04.27: Rather than just repeat what's in the database for the
     #             prevision branch version (and maybe losing precision since
     #             we fetched coverage_area using conf.db_fetch_precision),
     #             we can recalculate it: see: commit.py calls
     #             byway.Many.branch_coverage_area_update.
     restore_carea = self.coverage_area
     if self.coverage_area.startswith('M '):
         # There's no geometry.svg_polygon_to_xy like there's a svg_line_to_xy,
         # so we use the geometry-type agnostic gml.flat_to_xys rather than
         # just filling in the blanks in geometry.py and writing such a fcn.
         # And this is a little ugly: we have to close the polygon ring, and
         # we have to make it a multipolygon for our geometry translation.
         # (Instead of this dance, we could, e.g.,
         #  ST_AsEWKT(br.coverage_area) AS coverage_area_wkt.)
         # Note that we fetched coverage_area using conf.db_fetch_precision,
         # so we've lost precision, so the caller should make sure to call
         # byway.Many.branch_coverage_area_update if they care (commit does).
         coverage_pgon = gml.flat_to_xys(self.coverage_area)
         coverage_pgon.append(coverage_pgon[0])
         self.coverage_area = geometry.xy_to_ewkt_polygon(
             [
                 coverage_pgon,
             ], precision=conf.postgis_precision)
     self.save_insert(qb, One.item_type_table, One.psql_defns)
     # Restore the geometry to SVG (even though in practive save_core
     # is just used by commit, so the coverage_area is no longer needed,
     # and is about to be recomputed).
     self.coverage_area = restore_carea
Beispiel #23
0
 def from_gml(self, qb, elem):
     # Go through the schema cols and see which ones have input XML
     # configured. We have to go through the list twice, the second time
     # checking for attributes required only when creating a new item.
     pass_number = 1
     while pass_number and (pass_number <= 2):
         for defn in self.attr_defns:
             # The XML can be tagged either with the complete class attribute
             # name, or it can use an abbreviation.
             attr_synonyms = set()
             # The abbrev index is not defined for all defn tuples.
             try:
                 attr_name = defn[One.scol_abbrev] or defn[One.scol_pyname]
                 attr_synonyms.add(attr_name)
             except IndexError:
                 pass
             # The pyname index is always defined all each defn tuple.
             attr_synonyms.add(defn[One.scol_pyname])
             # Decide if we should look for this attribute in the input.
             try:
                 req_code = defn[One.scol_inreqd]
                 g.assurt(req_code in (
                     One.inreqd_illegal,
                     One.inreqd_optional,
                     One.inreqd_required_on_create,
                     One.inreqd_required_always,
                     # FIXME: Verify IP if inreqd_local_only
                     One.inreqd_local_only,
                     One.inreqd_optional_on_create,
                 ))
             except IndexError:
                 req_code = None
             # Try each of the GML names.
             found_attr = self.from_gml_defn(elem, defn, attr_synonyms,
                                             req_code, pass_number)
             # If required but not found, raise.
             if not found_attr:
                 if pass_number == 1:
                     required = (req_code == One.inreqd_required_always)
                 else:
                     g.assurt(pass_number == 2)
                     required = (req_code == One.inreqd_required_on_create)
                 if required:
                     # C.f. One.from_gml_required
                     raise GWIS_Error(
                         'Missing mandatory attr: one of "%s".' %
                         (attr_synonyms, ))
         # end for
         # EXPLAIN: When is stack_id not set? For routes being analyzed?
         #          (For 'analysis', isn't stack_id == 0?)
         if ((pass_number == 1)
                 and (hasattr(self, 'stack_id') and (self.stack_id < 0))):
             g.assurt(self.stack_id is not None)
             # Do a second pass and verify creation attrs are avail.
             pass_number = 2
         else:
             # MAYBE: inreqd_optional_on_create. Loop again and check that
             # optional creation arguments are *not* set...
             pass_number = 0
Beispiel #24
0
    def decode_request_item_type(self):
        '''
      Checks that item_type is a valid geofeature, attachment, or
      link_value. Since link_value is a factory class (of sorts), we also
      check that the geofeature and attachment types it references are
      valid.
         
      NOTE We could defer this check and the subsequent GWIS_Error to the
           link_value class constructor, but we do it here so we have the
           attachment and geofeature class handles handy for the link_value
           constructor (which also relieves the link_value class of having
           to verify the class types, which may or may not be a Good Thing).
      '''
        success = True
        # Every GML GetItem request requires an item_type
        self.item_type = self.decode_key('ityp')
        if ((self.item_type == 'link_value')
                or (self.item_type == 'link_geofeature')):
            # The link_value joins attachments and geofeatures; check that both
            # exist.
            # MAYBE: Let client specify item types by int ID, rather than string.
            self.item_attc_type = self.decode_key('atyp', None)
            self.item_feat_type = self.decode_key('ftyp', None)
            success = (item_factory.is_item_valid(self.item_attc_type)
                       and item_factory.is_item_valid(self.item_feat_type))
            # Check for success; throw now before further processing.
            if (not success):
                raise GWIS_Error(
                    'Invalid link_value type(s): attc: %s / feat: %s' % (
                        self.item_attc_type,
                        self.item_feat_type,
                    ))
        else:
            # Otherwise, item_type is a module in the item/ package.
            self.item_attc_type = None
            self.item_feat_type = None
            success = item_factory.is_item_valid(self.item_type, True)
            # Reid says, Barf on error.
            if not success:
                raise GWIS_Error('Invalid item type: ' + self.item_type)

        log.verbose1('decode_request_item_type: %s / lhs: %s / rhs: %s' % (
            self.item_type,
            self.item_attc_type,
            self.item_feat_type,
        ))
 def fetch_n_save(self):
     command.Op_Handler.fetch_n_save(self)
     self.xml = etree.Element('lmrk_exp')
     if ((not self.req.client.username)
             or (self.req.client.username == conf.anonymous_username)):
         raise GWIS_Error('User must be logged in.')
     else:
         self.get_trial()
Beispiel #26
0
   def routed_port_set(self, travel_mode):

      # Each route_get request only talks to one route server.

      g.assurt(travel_mode)

      if not self.routed_port:

         try:
            self.travel_mode = int(travel_mode)
         except ValueError:
            try:
               self.travel_mode = Travel_Mode.lookup[travel_mode]
            except KeyError:
               raise GWIS_Error('Unknown travel_mode: %s' % (travel_mode,))
         g.assurt(Travel_Mode.is_valid(self.travel_mode))

         if self.travel_mode not in Travel_Mode.px_modes:
            raise GWIS_Error('Not a planner travel_mode: %s' % (travel_mode,))

         # Query the database for a running routed for this branch/instance.
         # Since the client didn't specify the port, we assume they want the
         # 'general' route finder personality, i.e., not an analytics route 
         # finder personality.
         if self.travel_mode in Travel_Mode.p3_modes:
            # Travel_Mode.wayward, Travel_Mode.bicycle
            routed_pers = 'p3'
         elif self.travel_mode in Travel_Mode.p2_modes:
            # Travel_Mode.transit
            routed_pers = 'p2'
         elif self.travel_mode in Travel_Mode.p1_modes:
            # Travel_Mode.classic
            routed_pers = 'p1'
         else:
            g.assurt(False)

      # self.qb isn't set, so neither is self.qb.request_is_local.
      if ((self.req.client.request_is_local)
          and (conf.remote_routed_role == 'client')):
         self.routed_port = conf.remote_routed_port
      else:
         # This raises if the route finder is not running.
         self.routed_port = Routed_Ports.find_routed_port_num(
            self.req.db, self.req.branch.branch_id, routed_pers, 'general',
            self)
Beispiel #27
0
    def fetch_n_save(self):
        command.Op_Handler.fetch_n_save(self)

        # NOTE: This command fetches a page of results and can also calculate the
        #       total results count in one fell swoop. The commit class, on the
        #       other hand, forces callers to separate the two calls.
        # FIXME: Maybe commit should be more like this command, and do both at
        #        once.
        # Or, FIXME: Should this be how it works for item_user_access? Or should
        # this work like that? That is, should 'count' be returned with a list of
        # records, or should 'count' always be its own separate gwis request?

        qb = self.req.as_iqb()

        # Limit to just the leaf branch, so we only return its revisions.
        branch_hier_limit = qb.branch_hier_limit
        qb.branch_hier_limit = 1

        qb.use_filters_and_viewport = True

        if qb.filters.pagin_count:
            if qb.filters.pagin_count > conf.constraint_page_max:
                raise GWIS_Error('Count too large for item request (%s).' %
                                 (self.item_type, ))
            else:
                qb.use_limit_and_offset = True
        else:
            # It's, e.g., filter by revision ID, and filters.rev_ids is set.
            # See: query_filters.get_id_count(); this is similar. Also see
            #      commit.py, whence from we c.f. the gwis_errs.
            if len(qb.filters.rev_ids) == 0:
                raise GWIS_Error('Revision IDs missing from request (%s).' %
                                 (self.item_type, ))
            # MAGIC_NUMBER: conf.constraint_sids_max is large; when filtering by
            #               revision ID, let's do something reasonable, like 100?
            #               Currently, the user manually enters these numbers, so
            #               it doesn't need to be large.
            # elif len(qb.filters.rev_ids) > conf.constraint_sids_max:
            elif len(qb.filters.rev_ids) > Op_Handler.constraint_rids_max:
                raise GWIS_Error('Too many revision IDs in request (%s).' %
                                 (self.item_type, ))

        self.fetch_n_save_impl(qb)

        qb.branch_hier_limit = branch_hier_limit
Beispiel #28
0
 def verify_access_level(self, access_level_id, filter_abbrev):
     # The access level should be valid and not less than client, which is
     # what we normal use as the min access level when searching.
     if ((not Access_Level.is_valid(access_level_id))
             or (access_level_id > Access_Level.client)):
         raise GWIS_Error('Illegal value for "%s": %s.' % (
             filter_abbrev,
             access_level_id,
         ))
Beispiel #29
0
 def from_gml_group_id_(db, grp_id, grp_nm, required=True):
     group_id = None
     if bool(grp_id and grp_nm):
         raise GWIS_Error(
             'Attr. confusions: Please specify just "group_id" or "group_name"'
         )
     elif (not grp_id) and (not grp_nm):
         if required:
             raise GWIS_Error(
                 'Missing mandatory attr: "group_id" or "group_name"')
     elif not grp_id:
         group_id = Many.group_id_from_group_name(db, grp_nm)
         log.debug('from_gml: resolved group_id %d from group_name "%s".' %
                   (
                       group_id,
                       grp_nm,
                   ))
     return group_id
Beispiel #30
0
 def save_verify_creator_arbiter(self, qb):
     # BUG nnnn: This is a hack until posts' and threads' GIA records
     # are fixed. Currently, just one publicly-editable record is created.
     # Ideally, there'd be two records, one public-readable, and one
     # creator-editable/or-arbitable. But we're still left with how
     # to give branch arbiters edit-access to all users' threads and posts,
     # so arbiters can censor threads and posts... would that be controlled
     # by a GIA record for branch arbiters, or would it be controlled by
     # a new_item_policy record? For not, we do it in code: branch arbiters
     # can edit posts and threads.
     if self.version > 1:
         if qb.username == conf.anonymous_username:
             raise GWIS_Error('Must be item creator to edit said item.')
         try:
             branch.Many.branch_enforce_permissions(qb,
                                                    Access_Level.arbiter)
         except GWIS_Error, e:
             raise GWIS_Error('Not creator or branch arbiter too bad.')
Beispiel #31
0
 def __init__(self, message, tag=None, logger=log.error):
    GWIS_Error.__init__(self, message, tag, logger)
Beispiel #32
0
 def as_xml(self, elem_name='gwis_fatal'):
    xml = GWIS_Error.as_xml(self, elem_name)
    return xml