示例#1
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, DataFlowModel.required)
        json_dict[
            '__python_obj__'] = DataFlow.__module__ + '.' + DataFlow.__name__

        realDfos = []
        for dfo in json_dict['theObstacles']:
            check_required_keys(dfo, DataFlowObstacle.required)
            realDfos.append(
                (dfo['theObstacleName'], dfo['theKeyword'], dfo['theContext']))

        dataflow = json_serialize(json_dict)
        dataflow = json_deserialize(dataflow)
        dataflow.theObstacles = realDfos
        if not isinstance(dataflow, DataFlow):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return dataflow
示例#2
0
  def from_json(self, request):
    """
    :rtype : UseCase
    :raise MalformedJSONHTTPError:
    """
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, UseCaseModel.required)
    json_dict['__python_obj__'] = UseCase.__module__ + '.' + UseCase.__name__

    usecase_props = self.convert_props(fake_props=json_dict['theEnvironmentProperties'])
    json_dict['theEnvironmentProperties'] = []

    usecase = json_serialize(json_dict)
    usecase = json_deserialize(usecase)
    usecase.theEnvironmentProperties = usecase_props
     
    if not isinstance(usecase, UseCase):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      frcs = json_dict['theReferenceContributions']
      refContribs = []
      for frc in frcs:
        refContribs.append(ReferenceContribution(usecase.theName,frc['theContributionTo'],frc['theReferenceContribution']['theMeansEnd'],frc['theReferenceContribution']['theContribution']))
      return usecase,refContribs
示例#3
0
    def from_json(self, request):
        """
        :rtype : Attacker
        :raise MalformedJSONHTTPError:
        """
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, AttackerModel.required)
        json_dict['__python_obj__'] = Attacker.__module__ + '.' + Attacker.__name__

        attacker_props = self.convert_props(fake_props=json_dict['theEnvironmentProperties'])
        json_dict['theEnvironmentProperties'] = []

        attacker = json_serialize(json_dict)
        attacker = json_deserialize(attacker)
        attacker.theEnvironmentProperties = attacker_props
        if not isinstance(attacker, Attacker):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return attacker
示例#4
0
 def convert_loc_list(self,real_loc_list = None, fake_loc_list = None):
   new_loc_list = []
   if real_loc_list is not None:
     if len(real_loc_list) > 0:
       for real_loc in real_loc_list:
         assert isinstance(real_loc,Location)
         loc_dict = {}
         loc_dict['theName'] = real_loc.name()
         loc_dict['theAssetInstances'] = []  
         for ai in real_loc.assetInstances():
           loc_dict['theAssetInstances'].append({'theName':ai[0],'theAsset':ai[1]})  
         loc_dict['thePersonaInstances'] = []  
         for pi in real_loc.personaInstances():
           loc_dict['thePersonaInstances'].append({'theName':pi[0],'thePersona':pi[1]})  
         loc_dict['theLinks'] = real_loc.links()
         new_loc_list.append(loc_dict)
   elif fake_loc_list is not None:
     if len(fake_loc_list) > 0:
       for fake_loc in fake_loc_list:
         check_required_keys(fake_loc,LocationModel.required) 
         assetInstances = []
         for ai in fake_loc['theAssetInstances']:
           assetInstances.append((ai['theName'],ai['theAsset']))
         personaInstances = []
         for pi in fake_loc['thePersonaInstances']:
           personaInstances.append((pi['theName'],pi['thePersona']))
         new_loc_list.append(Location(-1,fake_loc['theName'],assetInstances,personaInstances,fake_loc['theLinks']))
   else:
     self.close()
     raise MissingParameterHTTPError(param_names=['real_loc_list', 'fake_loc_list'])
   return new_loc_list
示例#5
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, LocationsModel.required)
        json_dict[
            '__python_obj__'] = Locations.__module__ + '.' + Locations.__name__

        loc_list = self.convert_loc_list(
            fake_loc_list=json_dict['theLocations'])
        json_dict['theLocations'] = []

        locs = json_serialize(json_dict)
        locs = json_deserialize(locs)
        locs.theLocations = loc_list
        locs.theLinks = []

        if isinstance(locs, Locations):
            return locs
        else:
            self.close()
            raise MalformedJSONHTTPError()
示例#6
0
  def from_json(self, request):
    """
    :rtype : UseCase
    :raise MalformedJSONHTTPError:
    """
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, UseCaseModel.required)
    json_dict['__python_obj__'] = UseCase.__module__ + '.' + UseCase.__name__

    usecase_props = self.convert_props(fake_props=json_dict['theEnvironmentProperties'])
    json_dict['theEnvironmentProperties'] = []

    usecase = json_serialize(json_dict)
    usecase = json_deserialize(usecase)
    usecase.theEnvironmentProperties = usecase_props
     
    if not isinstance(usecase, UseCase):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      frcs = json_dict['theReferenceContributions']
      refContribs = []
      for frc in frcs:
        refContribs.append(ReferenceContribution(usecase.theName,frc['theContributionTo'],frc['theReferenceContribution']['theMeansEnd'],frc['theReferenceContribution']['theContribution']))
      return usecase,refContribs
示例#7
0
    def convert_props(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            if len(real_props) > 0:
                for real_prop in real_props:
                    assert isinstance(real_prop, AttackerEnvironmentProperties)
                    capabilities = []
                    for capability in real_prop.theCapabilities:
                        if len(capability) == 2:
                            capabilities.append({
                                'name': capability[0],
                                'value': capability[1]
                            })
                    real_prop.theCapabilities = capabilities
                    new_props.append(real_prop)
        elif fake_props is not None:
            if len(fake_props) > 0:
                for fake_prop in fake_props:
                    check_required_keys(fake_prop, AttackerEnvironmentPropertiesModel.required)
                    cap_list = []
                    assert isinstance(cap_list, list)
                    for cap in fake_prop['theCapabilities']:
                        cap_list.append((cap['name'], cap['value']))
                    new_prop = AttackerEnvironmentProperties(
                        environmentName=fake_prop['theEnvironmentName'],
                        roles=fake_prop['theRoles'],
                        motives=fake_prop['theMotives'],
                        capabilities=cap_list
                    )
                    new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['real_props', 'fake_props'])

        return new_props
示例#8
0
  def from_json(self, request,domain_name=None):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, RequirementModel.required)
    json_dict['__python_obj__'] = Requirement.__module__+'.'+Requirement.__name__
    json_dict['attrs'] = {}
    json_dict['dirtyAttrs'] = {}
    json_dict['theVersion'] = -1
    json_dict['attrs']['originator'] = json_dict['theOriginator']
    json_dict['attrs']['supportingMaterial'] = ''
    json_dict['attrs']['fitCriterion'] = json_dict['theFitCriterion']
     
    if (domain_name != None):
      json_dict['attrs']['asset'] = domain_name
    else:
      json_dict['attrs']['asset'] = json_dict['theDomain']
    json_dict['attrs']['rationale'] = json_dict['theRationale']
    json_dict['attrs']['type'] = json_dict['theType']
    requirement = json_serialize(json_dict)
    requirement = json_deserialize(requirement)
    if not isinstance(requirement, Requirement):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      requirement.theAsset = json_dict['attrs']['asset']
      return requirement
示例#9
0
    def from_json(self, request):
        """
    :rtype : Persona
    :raise MalformedJSONHTTPError:
    """
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, PersonaModel.required)
        json_dict[
            '__python_obj__'] = Persona.__module__ + '.' + Persona.__name__

        persona_props = self.convert_props(
            fake_props=json_dict['theEnvironmentProperties'])
        json_dict['theEnvironmentProperties'] = []

        persona = json_serialize(json_dict)
        persona = json_deserialize(persona)
        persona.theEnvironmentProperties = persona_props
        if not isinstance(persona, Persona):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return persona
示例#10
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, VulnerabilityModel.required)
        json_dict[
            '__python_obj__'] = Vulnerability.__module__ + '.' + Vulnerability.__name__

        for idx in range(0, len(json_dict['theEnvironmentProperties'])):
            property = json_dict['theEnvironmentProperties'][idx]
            check_required_keys(
                property, VulnerabilityEnvironmentPropertiesModel.required)
            property[
                '__python_obj__'] = VulnerabilityEnvironmentProperties.__module__ + '.' + VulnerabilityEnvironmentProperties.__name__
            json_dict['theEnvironmentProperties'][idx] = property

        vulnerability = json_serialize(json_dict)
        vulnerability = json_deserialize(vulnerability)
        if not isinstance(vulnerability, Vulnerability):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return vulnerability
示例#11
0
    def from_json(self, request):
        """
    :rtype : Attacker
    :raise MalformedJSONHTTPError:
    """
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, AttackerModel.required)
        json_dict[
            '__python_obj__'] = Attacker.__module__ + '.' + Attacker.__name__

        attacker_props = self.convert_props(
            fake_props=json_dict['theEnvironmentProperties'])
        json_dict['theEnvironmentProperties'] = []

        attacker = json_serialize(json_dict)
        attacker = json_deserialize(attacker)
        attacker.theEnvironmentProperties = attacker_props
        if not isinstance(attacker, Attacker):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return attacker
示例#12
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        assert isinstance(json_dict, dict)
        check_required_keys(json_dict, EnvironmentModel.required)
        json_dict['__python_obj__'] = Environment.__module__+'.'+Environment.__name__

        if json_dict.has_key('theTensions'):
            assert isinstance(json_dict['theTensions'], list)
            tensions = json_dict['theTensions']
            json_dict['theTensions'] = {}
            for tension in tensions:
                check_required_keys(tension, EnvironmentTensionModel.required)
                key = tuple([tension['base_attr_id'], tension['attr_id']])
                value = tuple([tension['value'], tension['rationale']])
                json_dict['theTensions'][key] = value

        new_json_environment = json_serialize(json_dict)
        environment = json_deserialize(new_json_environment)
        if not isinstance(environment, Environment):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return environment
示例#13
0
  def from_json(self, request):
    """
    :rtype : Persona
    :raise MalformedJSONHTTPError:
    """
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, PersonaModel.required)
    json_dict['__python_obj__'] = Persona.__module__ + '.' + Persona.__name__

    persona_props = self.convert_props(fake_props=json_dict['theEnvironmentProperties'])
    json_dict['theEnvironmentProperties'] = []

    persona = json_serialize(json_dict)
    persona = json_deserialize(persona)
    persona.theEnvironmentProperties = persona_props
    if not isinstance(persona, Persona):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      return persona
示例#14
0
  def from_json(self, request):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    assert isinstance(json_dict, dict)
    check_required_keys(json_dict, EnvironmentModel.required)
    json_dict['__python_obj__'] = Environment.__module__+'.'+Environment.__name__

    if 'theTensions' in json_dict:
      assert isinstance(json_dict['theTensions'], list)
      tensions = json_dict['theTensions']
      json_dict['theTensions'] = {}
      for tension in tensions:
        check_required_keys(tension, EnvironmentTensionModel.required)
        key = tuple([tension['base_attr_id'], tension['attr_id']])
        value = tuple([tension['value'], tension['rationale']])
        json_dict['theTensions'][key] = value

    json_dict['theId'] = -1
    new_json_environment = json_serialize(json_dict)
    environment = json_deserialize(new_json_environment)
    if not isinstance(environment, Environment):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      return environment
示例#15
0
 def convert_loc_list(self,real_loc_list = None, fake_loc_list = None):
   new_loc_list = []
   if real_loc_list is not None:
     if len(real_loc_list) > 0:
       for real_loc in real_loc_list:
         assert isinstance(real_loc,Location)
         loc_dict = {}
         loc_dict['theName'] = real_loc.name()
         loc_dict['theAssetInstances'] = []  
         for ai in real_loc.assetInstances():
           loc_dict['theAssetInstances'].append({'theName':ai[0],'theAsset':ai[1]})  
         loc_dict['thePersonaInstances'] = []  
         for pi in real_loc.personaInstances():
           loc_dict['thePersonaInstances'].append({'theName':pi[0],'thePersona':pi[1]})  
         loc_dict['theLinks'] = real_loc.links()
         new_loc_list.append(loc_dict)
   elif fake_loc_list is not None:
     if len(fake_loc_list) > 0:
       for fake_loc in fake_loc_list:
         check_required_keys(fake_loc,LocationModel.required) 
         assetInstances = []
         for ai in fake_loc['theAssetInstances']:
           assetInstances.append((ai['theName'],ai['theAsset']))
         personaInstances = []
         for pi in fake_loc['thePersonaInstances']:
           personaInstances.append((pi['theName'],pi['thePersona']))
         new_loc_list.append(Location(-1,fake_loc['theName'],assetInstances,personaInstances,fake_loc['theLinks']))
   else:
     self.close()
     raise MissingParameterHTTPError(param_names=['real_loc_list', 'fake_loc_list'])
   return new_loc_list
示例#16
0
    def from_json(self, request):
        """
    :rtype : Response
    :raise: MalformedJSONHTTPError:
    """
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, ResponseModel.required)
        json_dict[
            '__python_obj__'] = Response.__module__ + '.' + Response.__name__

        property_dict = json_dict['theEnvironmentProperties']
        try:
            real_props = self.convert_props(
                fake_props=property_dict,
                response_type=json_dict['theResponseType'])
            json_dict['theEnvironmentProperties'] = real_props

            json_resp = json_serialize(json_dict)
            response = json_deserialize(json_resp)

            if isinstance(response, Response):
                return response
            else:
                raise MalformedJSONHTTPError()
        except MalformedJSONHTTPError as ex:
            self.close()
            raise ex
示例#17
0
    def from_json(self, request, to_props=False):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, TemplateAssetModel.required)
        json_dict[
            '__python_obj__'] = TemplateAsset.__module__ + '.' + TemplateAsset.__name__
        ifs = json_dict.pop('theInterfaces', [])
        ifs = self.convert_ifs(fake_ifs=ifs)
        props = json_dict.pop('theProperties', [])
        ta = json_serialize(json_dict)
        props, rats = self.convert_props(fake_props=props)
        ta = json_deserialize(ta)

        if isinstance(ta, TemplateAsset):
            ta.theInterfaces = ifs
            ta.theProperties = props
            ta.theRationale = rats
            return ta
        else:
            self.close()
            raise MalformedJSONHTTPError()
示例#18
0
 def convert_props(self, real_props=None, fake_props=None):
     new_props = []
     if real_props is not None:
         if len(real_props) > 0:
             for real_prop in real_props:
                 assert isinstance(real_prop, PersonaEnvironmentProperties)
                 del real_prop.theCodes
                 new_props.append(real_prop)
     elif fake_props is not None:
         if len(fake_props) > 0:
             for fake_prop in fake_props:
                 check_required_keys(
                     fake_prop, PersonaEnvironmentPropertiesModel.required)
                 new_prop = PersonaEnvironmentProperties(
                     environmentName=fake_prop['theEnvironmentName'],
                     direct=fake_prop['theDirectFlag'],
                     description=fake_prop['theNarrative'],
                     roles=fake_prop['theRoles'],
                     pCodes=[])
                 new_props.append(new_prop)
     else:
         self.close()
         raise MissingParameterHTTPError(
             param_names=['real_props', 'fake_props'])
     return new_props
示例#19
0
  def convert_scores(self, real_scores=None, fake_scores=None):
    new_scores = []
    if real_scores:
      if len(real_scores) > 0:
        for idx in range(0, len(real_scores)):
          real_score = real_scores[idx]
          if len(real_score) == 4:
            new_score = RiskScore(response_name=real_score[0],unmit_score=real_score[1],mit_score=real_score[2],details=real_score[3])
            new_scores.append(new_score)
    elif fake_scores:
      if len(fake_scores) > 0:
        for idx in range(0, len(fake_scores)):
          fake_score = fake_scores[idx]
          assert isinstance(fake_score, RiskScore)
          check_required_keys(fake_score, RiskScore.required)
          if fake_score['unmitScore'] == -1:
            fake_score['unmitScore'] = None
          if fake_score['mitScore'] == -1:
            fake_score['mitScore'] = None
          new_score = (fake_score['responseName'], fake_score['unmitScore'], fake_score['mitScore'], fake_score['details'])
          new_scores.append(new_score)
    else:
      self.close()
      raise MissingParameterHTTPError(param_names=['scores'])

    return new_scores
示例#20
0
  def from_json(self, request,domain_name=None):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, RequirementModel.required)
    json_dict['__python_obj__'] = Requirement.__module__+'.'+Requirement.__name__
    json_dict['attrs'] = {}
    json_dict['dirtyAttrs'] = {}
    json_dict['theVersion'] = -1
    json_dict['attrs']['originator'] = json_dict['theOriginator']
    json_dict['attrs']['supportingMaterial'] = ''
    json_dict['attrs']['fitCriterion'] = json_dict['theFitCriterion']
     
    if (domain_name != None):
      json_dict['attrs']['asset'] = domain_name
    else:
      json_dict['attrs']['asset'] = json_dict['theDomain']
    json_dict['attrs']['rationale'] = json_dict['theRationale']
    json_dict['attrs']['type'] = json_dict['theType']
    requirement = json_serialize(json_dict)
    requirement = json_deserialize(requirement)
    if not isinstance(requirement, Requirement):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      return requirement
示例#21
0
文件: TaskDAO.py 项目: adamrbu/cairis
  def from_json(self, request):
    """
    :rtype : Task
    :raise MalformedJSONHTTPError:
    """
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, TaskModel.required)
    json_dict['__python_obj__'] = Task.__module__ + '.' + Task.__name__

    task_props = self.convert_props(fake_props=json_dict['theEnvironmentProperties'])
    json_dict['theEnvironmentProperties'] = []

    task = json_serialize(json_dict)
    task = json_deserialize(task)
    task.theEnvironmentProperties = task_props
    if not isinstance(task, Task):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      return task
示例#22
0
    def from_json(self, request):
        """
    :rtype : UseCase
    :raise MalformedJSONHTTPError:
    """
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, UseCaseModel.required)
        json_dict[
            '__python_obj__'] = UseCase.__module__ + '.' + UseCase.__name__

        usecase_props = self.convert_props(
            fake_props=json_dict['theEnvironmentProperties'])
        json_dict['theEnvironmentProperties'] = []

        usecase = json_serialize(json_dict)
        usecase = json_deserialize(usecase)
        usecase.theEnvironmentProperties = usecase_props
        if not isinstance(usecase, UseCase):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return usecase
示例#23
0
文件: RiskDAO.py 项目: failys/cairis
  def convert_scores(self, real_scores=None, fake_scores=None):
    new_scores = []
    if real_scores:
      if len(real_scores) > 0:
        for idx in range(0, len(real_scores)):
          real_score = real_scores[idx]
          if len(real_score) == 4:
            new_score = RiskScore(response_name=real_score[0],unmit_score=real_score[1],mit_score=real_score[2],details=real_score[3])
            new_scores.append(new_score)
    elif fake_scores:
      if len(fake_scores) > 0:
        for idx in range(0, len(fake_scores)):
          fake_score = fake_scores[idx]
          assert isinstance(fake_score, RiskScore)
          check_required_keys(fake_score, RiskScore.required)
          if fake_score['unmitScore'] == -1:
            fake_score['unmitScore'] = None
          if fake_score['mitScore'] == -1:
            fake_score['mitScore'] = None
          new_score = (fake_score['responseName'], fake_score['unmitScore'], fake_score['mitScore'], fake_score['details'])
          new_scores.append(new_score)
    else:
      self.close()
      raise MissingParameterHTTPError(param_names=['scores'])

    return new_scores
示例#24
0
  def from_json(self, request):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, ResponseModel.required)
    json_dict['__python_obj__'] = Response.__module__+'.'+Response.__name__

    property_dict = json_dict['theEnvironmentProperties']
    try:
      real_props = self.convert_props(fake_props=property_dict, response_type=json_dict['theResponseType'])
      json_dict['theEnvironmentProperties'] = real_props

      json_resp = json_serialize(json_dict)
      response = json_deserialize(json_resp)

      if isinstance(response, Response):
        return response
      else:
        raise MalformedJSONHTTPError()
    except MalformedJSONHTTPError as ex:
      self.close()
      raise ex
示例#25
0
  def from_json(self, request):
    """
    :rtype : Countermeasure
    :raise MalformedJSONHTTPError:
    """
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, CountermeasureModel.required)
    json_dict['__python_obj__'] = Countermeasure.__module__ + '.' + Countermeasure.__name__

    countermeasure_props = self.convert_props(fake_props=json_dict['theEnvironmentProperties'])
    json_dict['theEnvironmentProperties'] = []

    countermeasure = json_serialize(json_dict)
    countermeasure = json_deserialize(countermeasure)
    countermeasure.theEnvironmentProperties = countermeasure_props
    if not isinstance(countermeasure, Countermeasure):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      return countermeasure
示例#26
0
    def from_json(self, request, to_props=False):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, AssetModel.required)
        json_dict['__python_obj__'] = Asset.__module__ + '.' + Asset.__name__
        env_props = json_dict.pop('theEnvironmentProperties', [])
        env_props = self.convert_props(fake_props=env_props)
        ifs = json_dict.pop('theInterfaces', [])
        ifs = self.convert_ifs(fake_ifs=ifs)
        json_dict.pop('theEnvironmentDictionary', None)
        json_dict.pop('theAssetPropertyDictionary', None)
        asset = json_serialize(json_dict)
        asset = json_deserialize(asset)

        if isinstance(asset, Asset):
            asset.theInterfaces = ifs
            asset.theEnvironmentProperties = env_props
            return asset
        else:
            self.close()
            raise MalformedJSONHTTPError()
示例#27
0
 def convert_props(self, real_props=None, fake_props=None):
   new_props = []
   if real_props is not None:
     if len(real_props) > 0:
       for real_prop in real_props:
         assert isinstance(real_prop, UseCaseEnvironmentProperties)
         s = []
         for step in real_prop.steps().theSteps:
           s.append(StepAttributes(step.text(),step.synopsis(),step.actor(),step.actorType(),step.tags())) 
         real_prop.theSteps = s
         new_props.append(real_prop)
   elif fake_props is not None:
     if len(fake_props) > 0:
       for fake_prop in fake_props:
         check_required_keys(fake_prop, UseCaseEnvironmentPropertiesModel.required)
         steps = Steps()
         for s in fake_prop['theSteps']:
           steps.append(Step(s['theStepText'],s['theSynopsis'],s['theActor'],s['theActorType'],s['theTags']))
         fake_prop['theSteps'] = steps
         
         new_prop = UseCaseEnvironmentProperties(
                      environmentName=fake_prop['theEnvironmentName'],
                      preCond=fake_prop['thePreCond'],
                      steps=fake_prop['theSteps'],
                      postCond=fake_prop['thePostCond']
                    )
         new_props.append(new_prop)
   else:
     self.close()
     raise MissingParameterHTTPError(param_names=['real_props', 'fake_props'])
   return new_props
示例#28
0
    def from_json(self, request, to_props=False):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        if to_props and isinstance(json_dict, list):
            props = self.convert_props(fake_props=json_dict)
            return props
        else:
            assert isinstance(json_dict, dict)
            check_required_keys(json_dict, AssetModel.required)
            json_dict['__python_obj__'] = Asset.__module__+'.'+Asset.__name__
            env_props = json_dict.pop('theEnvironmentProperties', [])
            env_props = self.convert_props(fake_props=env_props)
            json_dict.pop('theEnvironmentDictionary', None)
            json_dict.pop('theAssetPropertyDictionary', None)
            asset = json_serialize(json_dict)
            asset = json_deserialize(asset)

            if isinstance(asset, Asset):
                asset.theEnvironmentProperties = env_props
                return asset
            else:
                self.close()
                raise MalformedJSONHTTPError()
示例#29
0
 def convert_props(self, real_props=None, fake_props=None):
   new_props = []
   if real_props is not None:
     if len(real_props) > 0:
       for real_prop in real_props:
         assert isinstance(real_prop, TaskEnvironmentProperties)
         new_props.append(real_prop)
   elif fake_props is not None:
     if len(fake_props) > 0:
       for fake_prop in fake_props:
         check_required_keys(fake_prop, TaskEnvironmentPropertiesModel.required)
         new_prop = TaskEnvironmentProperties(
                      environmentName=fake_prop['theEnvironmentName'],
                      deps=fake_prop['theDependencies'],
                      personas=fake_prop['thePersonas'],
                      assets=fake_prop['theAssets'],
                      concs=fake_prop['theConcernAssociations'],
                      narrative=fake_prop['theNarrative'],
                      consequences=fake_prop['theConsequences'],
                      benefits=fake_prop['theBenefits'],
                      tCodes=fake_prop['theCodes']
                    )
         new_props.append(new_prop)
   else:
     self.close()
     raise MissingParameterHTTPError(param_names=['real_props', 'fake_props'])
   return new_props
示例#30
0
  def from_json(self, request):
    """
    :rtype : Task
    :raise MalformedJSONHTTPError:
    """
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, TaskModel.required)
    json_dict['__python_obj__'] = Task.__module__ + '.' + Task.__name__

    task_props = self.convert_props(fake_props=json_dict['theEnvironmentProperties'])
    json_dict['theEnvironmentProperties'] = []

    task = json_serialize(json_dict)
    task = json_deserialize(task)
    task.theEnvironmentProperties = task_props
    if not isinstance(task, Task):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      return task
示例#31
0
文件: TaskDAO.py 项目: we45/cairis
    def convert_props(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            if len(real_props) > 0:
                for real_prop in real_props:
                    assert isinstance(real_prop, TaskEnvironmentProperties)
                    del real_prop.theCodes
                    ptList = []
                    for ptc in real_prop.personas():
                        ptList.append(
                            PersonaTaskCharacteristics(ptc[0], ptc[1], ptc[2],
                                                       ptc[3], ptc[4]))
                    real_prop.thePersonas = ptList
                    gcaList = []
                    for gca in real_prop.concernAssociations():
                        gcaList.append(
                            ConcernAssociationModel(gca[0], gca[1], gca[2],
                                                    gca[3], gca[4]))
                    real_prop.theConcernAssociations = gcaList
                    new_props.append(real_prop)
        elif fake_props is not None:
            if len(fake_props) > 0:
                for fake_prop in fake_props:
                    check_required_keys(
                        fake_prop, TaskEnvironmentPropertiesModel.required)
                    ptList = []
                    for ptc in fake_prop['thePersonas']:
                        ptList.append([
                            ptc['thePersona'], ptc['theDuration'],
                            ptc['theFrequency'], ptc['theDemands'],
                            ptc['theGoalConflict']
                        ])
                    fake_prop['thePersonas'] = ptList
                    gcaList = []
                    for gca in fake_prop['theConcernAssociations']:
                        gcaList.append([
                            gca['theSource'], gca['theSourceNry'],
                            gca['theLinkVerb'], gca['theTarget'],
                            gca['theTargetNry']
                        ])
                    fake_prop['theConcernAssociations'] = gcaList

                    new_prop = TaskEnvironmentProperties(
                        environmentName=fake_prop['theEnvironmentName'],
                        deps=fake_prop['theDependencies'],
                        personas=fake_prop['thePersonas'],
                        assets=fake_prop['theAssets'],
                        concs=fake_prop['theConcernAssociations'],
                        narrative=fake_prop['theNarrative'],
                        consequences=fake_prop['theConsequences'],
                        benefits=fake_prop['theBenefits'],
                        tCodes=[])
                    new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])
        return new_props
示例#32
0
    def convert_props(self, real_props=None, fake_props=None, response_type=None):
        """
        :type real_props: list
        :type fake_props: dict[str,list[dict]]
        :type response_type: str
        """
        response_type = response_type.lower()

        if real_props:
            new_props_list = []
            for idx in range(0, len(real_props)):
                real_prop = real_props[idx]
                if isinstance(real_prop, AcceptEnvironmentProperties) and response_type == 'accept':
                    new_props_list.append(real_prop)
                elif isinstance(real_prop, MitigateEnvironmentProperties) and response_type == 'mitigate':
                    new_props_list.append(real_prop)
                elif isinstance(real_prop, TransferEnvironmentProperties) and response_type == 'transfer':
                    roles = real_prop.theRoles
                    for idx in range(0, len(roles)):
                        roles[idx] = ValuedRole(roles[idx][0], roles[idx][1])
                    real_prop.theRoles = roles
                    new_props_list.append(real_prop)
            new_props = { response_type: new_props_list }
        elif fake_props:
            new_props = []
            if not (response_type in ResponseEnvironmentPropertiesModel.field_names):
#            if not (response_type in ResponseEnvironmentPropertiesModel.field_names and fake_props.has_key(response_type)):
                raise MalformedJSONHTTPError()

#            fake_props = fake_props[response_type]
            if response_type == 'accept':
                model_class = AcceptEnvironmentPropertiesModel
                target_class = AcceptEnvironmentProperties
            elif response_type == 'mitigate':
                model_class = MitigateEnvironmentPropertiesModel
                target_class = MitigateEnvironmentProperties
            elif response_type == 'transfer':
                model_class = TransferEnvironmentPropertiesModel
                target_class = TransferEnvironmentProperties
            else:
                raise MalformedJSONHTTPError()

            for fake_prop in fake_props:
                check_required_keys(fake_prop, model_class.required)
                fake_prop['__python_obj__'] = target_class.__module__+'.'+target_class.__name__
                if target_class is TransferEnvironmentProperties:
                    roles = []
                    if isinstance(fake_prop['theRoles'], list):
                        for role in fake_prop['theRoles']:
                            check_required_keys(role, ValuedRole.required)
                            roles.append((role['roleName'], role['cost']))
                    fake_prop['theRoles'] = roles
                new_props.append(fake_prop)
        else:
            self.close()
            raise MalformedJSONHTTPError()

        return new_props
示例#33
0
文件: GoalDAO.py 项目: adamrbu/cairis
    def convert_properties(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            for real_prop in real_props:
                assert isinstance(real_prop, GoalEnvironmentProperties)

                new_concern_assocs = []
                for concern_assoc in real_prop.theConcernAssociations:
                    new_concern_assocs.append(list(concern_assoc))

                new_goal_refinements = []
                for goal_refinement in real_prop.theGoalRefinements:
                    new_goal_refinements.append(list(goal_refinement))

                new_subgoal_refinements = []
                for subgoal_refinement in real_prop.theSubGoalRefinements:
                    new_subgoal_refinements.append(list(subgoal_refinement))

                real_prop.theConcernAssociations = new_concern_assocs
                real_prop.theGoalRefinements = new_goal_refinements
                real_prop.theSubGoalRefinements = new_subgoal_refinements
                new_props.append(real_prop)
        elif fake_props is not None:
            for fake_prop in fake_props:
                check_required_keys(fake_prop,
                                    GoalEnvironmentPropertiesModel.required)

                new_concern_assocs = []
                for concern_assoc in fake_prop['theConcernAssociations']:
                    new_concern_assocs.append(tuple(concern_assoc))

                new_goal_refinements = []
                for goal_refinement in fake_prop['theGoalRefinements']:
                    new_goal_refinements.append(tuple(goal_refinement))

                new_subgoal_refinements = []
                for subgoal_refinement in fake_prop['theSubGoalRefinements']:
                    new_subgoal_refinements.append(tuple(subgoal_refinement))

                new_prop = GoalEnvironmentProperties(
                    environmentName=fake_prop['theEnvironmentName'],
                    lbl=fake_prop['theLabel'],
                    definition=fake_prop['theDefinition'],
                    category=fake_prop['theCategory'],
                    priority=fake_prop['thePriority'],
                    fitCriterion=fake_prop['theFitCriterion'],
                    issue=fake_prop['theIssue'],
                    goalRefinements=new_goal_refinements,
                    subGoalRefinements=new_subgoal_refinements,
                    concs=fake_prop['theConcerns'],
                    cas=new_concern_assocs)
                new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])

        return new_props
示例#34
0
    def convert_properties(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            for real_prop in real_props:
                assert isinstance(real_prop, ObstacleEnvironmentProperties)
                del real_prop.theLabel

                new_goal_refinements = []
                for gr in real_prop.theGoalRefinements:
                    new_goal_refinements.append(
                        RefinementModel(gr[0], gr[1], gr[2], gr[3], gr[4]))

                new_subgoal_refinements = []
                for sgr in real_prop.theSubGoalRefinements:
                    new_subgoal_refinements.append(
                        RefinementModel(sgr[0], sgr[1], sgr[2], sgr[3],
                                        sgr[4]))

                real_prop.theGoalRefinements = new_goal_refinements
                real_prop.theSubGoalRefinements = new_subgoal_refinements
                new_props.append(real_prop)
        elif fake_props is not None:
            for fake_prop in fake_props:
                check_required_keys(
                    fake_prop, ObstacleEnvironmentPropertiesModel.required)

                new_goal_refinements = []
                for gr in fake_prop['theGoalRefinements']:
                    new_goal_refinements.append(
                        (gr['theEndName'], gr['theEndType'], gr['theRefType'],
                         gr['isAlternate'], gr['theRationale']))

                new_subgoal_refinements = []
                for sgr in fake_prop['theSubGoalRefinements']:
                    new_subgoal_refinements.append(
                        (sgr['theEndName'], sgr['theEndType'],
                         sgr['theRefType'], sgr['isAlternate'],
                         sgr['theRationale']))

                new_prop = ObstacleEnvironmentProperties(
                    environmentName=fake_prop['theEnvironmentName'],
                    lbl='',
                    definition=fake_prop['theDefinition'],
                    category=fake_prop['theCategory'],
                    gRefs=new_goal_refinements,
                    sgRefs=new_subgoal_refinements,
                    concs=fake_prop['theConcerns'])
                new_prop.theProbability = fake_prop['theProbability']
                new_prop.theProbabilityRationale = fake_prop[
                    'theProbabilityRationale']
                new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])

        return new_props
示例#35
0
    def convert_properties(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            for real_prop in real_props:
                assert isinstance(real_prop, GoalEnvironmentProperties)

                new_concern_assocs = []
                for concern_assoc in real_prop.theConcernAssociations:
                    new_concern_assocs.append(list(concern_assoc))

                new_goal_refinements = []
                for goal_refinement in real_prop.theGoalRefinements:
                    new_goal_refinements.append(list(goal_refinement))

                new_subgoal_refinements = []
                for subgoal_refinement in real_prop.theSubGoalRefinements:
                    new_subgoal_refinements.append(list(subgoal_refinement))

                real_prop.theConcernAssociations = new_concern_assocs
                real_prop.theGoalRefinements = new_goal_refinements
                real_prop.theSubGoalRefinements = new_subgoal_refinements
                new_props.append(real_prop)
        elif fake_props is not None:
            for fake_prop in fake_props:
                check_required_keys(fake_prop, GoalEnvironmentPropertiesModel.required)

                new_concern_assocs = []
                for concern_assoc in fake_prop['theConcernAssociations']:
                    new_concern_assocs.append(tuple(concern_assoc))

                new_goal_refinements = []
                for goal_refinement in fake_prop['theGoalRefinements']:
                    new_goal_refinements.append(tuple(goal_refinement))

                new_subgoal_refinements = []
                for subgoal_refinement in fake_prop['theSubGoalRefinements']:
                    new_subgoal_refinements.append(tuple(subgoal_refinement))

                new_prop = GoalEnvironmentProperties(
                    environmentName=fake_prop['theEnvironmentName'],
                    lbl=fake_prop['theLabel'],
                    definition=fake_prop['theDefinition'],
                    category=fake_prop['theCategory'],
                    priority=fake_prop['thePriority'],
                    fitCriterion=fake_prop['theFitCriterion'],
                    issue=fake_prop['theIssue'],
                    goalRefinements=new_goal_refinements,
                    subGoalRefinements=new_subgoal_refinements,
                    concs=fake_prop['theConcerns'],
                    cas=new_concern_assocs,
                )
                new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(param_names=['real_props', 'fake_props'])

        return new_props
示例#36
0
  def convert_properties(self, real_props=None, fake_props=None):
    new_props = []
    if real_props is not None:
      for real_prop in real_props:
        assert isinstance(real_prop, GoalEnvironmentProperties)
        del real_prop.theLabel
        new_concern_assocs = []
        for concern_assoc in real_prop.theConcernAssociations:
          new_concern_assocs.append(ConcernAssociationModel(concern_assoc[0],concern_assoc[1],concern_assoc[2],concern_assoc[3],concern_assoc[4]))

        new_goal_refinements = []
        for gr in real_prop.theGoalRefinements:
          new_goal_refinements.append(RefinementModel(gr[0],gr[1],gr[2],gr[3],gr[4]))

        new_subgoal_refinements = []
        for sgr in real_prop.theSubGoalRefinements:
          new_subgoal_refinements.append(RefinementModel(sgr[0],sgr[1],sgr[2],sgr[3],sgr[4]))

        real_prop.theConcernAssociations = new_concern_assocs
        real_prop.theGoalRefinements = new_goal_refinements
        real_prop.theSubGoalRefinements = new_subgoal_refinements
        new_props.append(real_prop)
    elif fake_props is not None:
      for fake_prop in fake_props:
        check_required_keys(fake_prop, GoalEnvironmentPropertiesModel.required)

        new_concern_assocs = []
        for concern_assoc in fake_prop['theConcernAssociations']:
          new_concern_assocs.append([concern_assoc['theSource'],concern_assoc['theSourceNry'],concern_assoc['theLinkVerb'],concern_assoc['theTarget'],concern_assoc['theTargetNry']])

        new_goal_refinements = []
        for gr in fake_prop['theGoalRefinements']:
          new_goal_refinements.append((gr['theEndName'],gr['theEndType'],gr['theRefType'],gr['isAlternate'],gr['theRationale']))

        new_subgoal_refinements = []
        for sgr in fake_prop['theSubGoalRefinements']:
          new_subgoal_refinements.append((sgr['theEndName'],sgr['theEndType'],sgr['theRefType'],sgr['isAlternate'],sgr['theRationale']))

        new_prop = GoalEnvironmentProperties(
          environmentName=fake_prop['theEnvironmentName'],
          lbl='',
          definition=fake_prop['theDefinition'],
          category=fake_prop['theCategory'],
          priority=fake_prop['thePriority'],
          fitCriterion=fake_prop['theFitCriterion'],
          issue=fake_prop['theIssue'],
          goalRefinements=new_goal_refinements,
          subGoalRefinements=new_subgoal_refinements,
          concs=fake_prop['theConcerns'],
          cas=new_concern_assocs)
        new_props.append(new_prop)
    else:
      self.close()
      raise MissingParameterHTTPError(param_names=['real_props', 'fake_props'])

    return new_props
示例#37
0
文件: GoalDAO.py 项目: failys/cairis
  def convert_properties(self, real_props=None, fake_props=None):
    new_props = []
    if real_props is not None:
      for real_prop in real_props:
        assert isinstance(real_prop, GoalEnvironmentProperties)
        del real_prop.theLabel
        new_concern_assocs = []
        for concern_assoc in real_prop.theConcernAssociations:
          new_concern_assocs.append(ConcernAssociationModel(concern_assoc[0],concern_assoc[1],concern_assoc[2],concern_assoc[3],concern_assoc[4]))

        new_goal_refinements = []
        for gr in real_prop.theGoalRefinements:
          new_goal_refinements.append(RefinementModel(gr[0],gr[1],gr[2],gr[3],gr[4]))

        new_subgoal_refinements = []
        for sgr in real_prop.theSubGoalRefinements:
          new_subgoal_refinements.append(RefinementModel(sgr[0],sgr[1],sgr[2],sgr[3],sgr[4]))

        real_prop.theConcernAssociations = new_concern_assocs
        real_prop.theGoalRefinements = new_goal_refinements
        real_prop.theSubGoalRefinements = new_subgoal_refinements
        new_props.append(real_prop)
    elif fake_props is not None:
      for fake_prop in fake_props:
        check_required_keys(fake_prop, GoalEnvironmentPropertiesModel.required)

        new_concern_assocs = []
        for concern_assoc in fake_prop['theConcernAssociations']:
          new_concern_assocs.append([concern_assoc['theSource'],concern_assoc['theSourceNry'],concern_assoc['theLinkVerb'],concern_assoc['theTarget'],concern_assoc['theTargetNry']])

        new_goal_refinements = []
        for gr in fake_prop['theGoalRefinements']:
          new_goal_refinements.append((gr['theEndName'],gr['theEndType'],gr['theRefType'],gr['isAlternate'],gr['theRationale']))

        new_subgoal_refinements = []
        for sgr in fake_prop['theSubGoalRefinements']:
          new_subgoal_refinements.append((sgr['theEndName'],sgr['theEndType'],sgr['theRefType'],sgr['isAlternate'],sgr['theRationale']))

        new_prop = GoalEnvironmentProperties(
          environmentName=fake_prop['theEnvironmentName'],
          lbl='',
          definition=fake_prop['theDefinition'],
          category=fake_prop['theCategory'],
          priority=fake_prop['thePriority'],
          fitCriterion=fake_prop['theFitCriterion'],
          issue=fake_prop['theIssue'],
          goalRefinements=new_goal_refinements,
          subGoalRefinements=new_subgoal_refinements,
          concs=fake_prop['theConcerns'],
          cas=new_concern_assocs)
        new_props.append(new_prop)
    else:
      self.close()
      raise MissingParameterHTTPError(param_names=['real_props', 'fake_props'])

    return new_props
示例#38
0
 def from_json(self, request):
     json_dict = super(DependencyDAO, self).from_json(request)
     check_required_keys(json_dict, DependencyModel.required)
     json_dict["__python_obj__"] = Dependency.__module__ + "." + Dependency.__name__
     dependency = json_deserialize(json_dict)
     if isinstance(dependency, Dependency):
         return dependency
     else:
         self.close()
         raise MalformedJSONHTTPError(json_serialize(json_dict))
示例#39
0
 def from_json(self, request):
     json_dict = super(DependencyDAO, self).from_json(request)
     check_required_keys(json_dict, DependencyModel.required)
     json_dict[
         '__python_obj__'] = Dependency.__module__ + '.' + Dependency.__name__
     dependency = json_deserialize(json_dict)
     if isinstance(dependency, Dependency):
         return dependency
     else:
         self.close()
         raise MalformedJSONHTTPError(json_serialize(json_dict))
示例#40
0
  def post(self):
    session_id = get_session_id(session, request)
    json_dict = request.get_json(silent=True)
    if json_dict is False or json_dict is None:
      raise MalformedJSONHTTPError(data=request.get_data())

    cimport_params = json_dict.get('object', None)
    check_required_keys(cimport_params or {}, CImportParams.required)
    file_contents = cimport_params['urlenc_file_contents']
    file_contents = unquote(file_contents)
    file_contents = file_contents.replace("\u2018", "'").replace("\u2019", "'")
    overwrite = cimport_params['overwrite']
    type = cimport_params['type']

    if file_contents.startswith('<?xml'):
      fd, abs_path = mkstemp(suffix='.xml')
      fs_temp = codecs.open(abs_path, 'w','utf-8')
      fs_temp.write(file_contents)
      fs_temp.close()
      fd_close(fd)

      try:
        dao = ImportDAO(session_id)
        result = dao.file_import(abs_path, type, overwrite)
        dao.close()
      except DatabaseProxyException as ex:
        raise ARMHTTPError(ex)
      except ARMException as ex:
        raise ARMHTTPError(ex)
      except Exception as ex:
        raise CairisHTTPError(status_code=500,message=str(ex.message),status='Unknown error')

      remove_file(abs_path)

      resp_dict = {'message': str(result)}
      resp = make_response(json_serialize(resp_dict, session_id=session_id), OK)
      resp.headers['Content-Type'] = 'application/json'
      return resp
    elif type == 'Attack Tree (Dot)':
      try:
        environment_name = cimport_params['environment']
        contributor_name = cimport_params['contributor']
        dao = ImportDAO(session_id)
        result = dao.import_attack_tree(file_contents,environment_name,contributor_name)
        dao.close()
      except DatabaseProxyException as ex:
        raise ARMHTTPError(ex)
      except ARMException as ex:
        raise ARMHTTPError(ex)
      except Exception as ex:
        raise CairisHTTPError(status_code=500,message=str(ex.message),status='Unknown error')
    else:
      raise CairisHTTPError(status_code=BAD_REQUEST,message='The provided file is not a valid XML file',status='Invalid XML input')
示例#41
0
    def convert_props(self, real_props=None, fake_props=None):
        new_props = []
        if real_props is not None:
            if len(real_props) > 0:
                for real_prop in real_props:
                    assert isinstance(real_prop, UseCaseEnvironmentProperties)
                    s = []
                    for step in real_prop.steps().theSteps:
                        excs = []
                        for excKey in step.exceptions():
                            exc = step.exception(excKey)
                            excs.append(
                                ExceptionAttributes(exc[0], exc[1], exc[2],
                                                    exc[3], exc[4]))
                        s.append(
                            StepAttributes(step.text(), step.synopsis(),
                                           step.actor(), step.actorType(),
                                           step.tags(), excs))
                    real_prop.theSteps = s
                    new_props.append(real_prop)
        elif fake_props is not None:
            if len(fake_props) > 0:
                for fake_prop in fake_props:
                    check_required_keys(
                        fake_prop, UseCaseEnvironmentPropertiesModel.required)
                    steps = Steps()
                    for fs in fake_prop['theSteps']:
                        aStep = Step(fs['theStepText'], fs['theSynopsis'],
                                     fs['theActor'], fs['theActorType'],
                                     fs['theTags'])
                        for exc in fs['theExceptions']:
                            aStep.addException(
                                (exc['theName'], exc['theDimensionType'],
                                 exc['theDimensionValue'],
                                 exc['theCategoryName'],
                                 exc['theDescription']))
                        steps.append(aStep)
                    fake_prop['theSteps'] = steps

                    new_prop = UseCaseEnvironmentProperties(
                        environmentName=fake_prop['theEnvironmentName'],
                        preCond=fake_prop['thePreCond'],
                        steps=fake_prop['theSteps'],
                        postCond=fake_prop['thePostCond'])
                    new_props.append(new_prop)
        else:
            self.close()
            raise MissingParameterHTTPError(
                param_names=['real_props', 'fake_props'])
        return new_props
示例#42
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, RoleModel.required)
        json_dict['__python_obj__'] = Role.__module__ + '.' + Role.__name__
        role = json_serialize(json_dict)
        role = json_deserialize(role)
        if not isinstance(role, Role):
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())
        else:
            return role
示例#43
0
  def from_json(self, request, to_props=False):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, AssetAssociationModel.required)
    json_dict['__python_obj__'] = ClassAssociation.__module__+'.'+ClassAssociation.__name__
    assoc = json_serialize(json_dict)
    assoc = json_deserialize(assoc)

    if isinstance(assoc, ClassAssociation):
      return assoc
    else:
      self.close()
      raise MalformedJSONHTTPError()
示例#44
0
  def from_json(self, request, to_props=False):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, ConceptReferenceModel.required)
    json_dict['__python_obj__'] = ConceptReference.__module__+'.'+ ConceptReference.__name__
    cr = json_serialize(json_dict)
    cr = json_deserialize(cr)

    if isinstance(cr, ConceptReference):
      return cr
    else:
      self.close()
      raise MalformedJSONHTTPError()
示例#45
0
文件: TaskDAO.py 项目: failys/cairis
 def convert_props(self, real_props=None, fake_props=None):
   new_props = []
   if real_props is not None:
     if len(real_props) > 0:
       for real_prop in real_props:
         assert isinstance(real_prop, TaskEnvironmentProperties)
         del real_prop.theCodes
         ptList = []
         for ptc in real_prop.personas():
           ptList.append(PersonaTaskCharacteristics(ptc[0],ptc[1],ptc[2],ptc[3],ptc[4])) 
         real_prop.thePersonas = ptList
         gcaList = []
         for gca in real_prop.concernAssociations():
           gcaList.append(ConcernAssociationModel(gca[0],gca[1],gca[2],gca[3],gca[4])) 
         real_prop.theConcernAssociations = gcaList
         new_props.append(real_prop)
   elif fake_props is not None:
     if len(fake_props) > 0:
       for fake_prop in fake_props:
         check_required_keys(fake_prop, TaskEnvironmentPropertiesModel.required)
         ptList = [] 
         for ptc in fake_prop['thePersonas']:
           ptList.append([ptc['thePersona'],ptc['theDuration'],ptc['theFrequency'],ptc['theDemands'],ptc['theGoalConflict']]) 
         fake_prop['thePersonas'] = ptList
         gcaList = []
         for gca in fake_prop['theConcernAssociations']:
           gcaList.append([gca['theSource'],gca['theSourceNry'],gca['theLinkVerb'],gca['theTarget'],gca['theTargetNry']]) 
         fake_prop['theConcernAssociations'] = gcaList
        
         
         new_prop = TaskEnvironmentProperties(
                      environmentName=fake_prop['theEnvironmentName'],
                      deps=fake_prop['theDependencies'],
                      personas=fake_prop['thePersonas'],
                      assets=fake_prop['theAssets'],
                      concs=fake_prop['theConcernAssociations'],
                      narrative=fake_prop['theNarrative'],
                      consequences=fake_prop['theConsequences'],
                      benefits=fake_prop['theBenefits'],
                      tCodes=[]
                    )
         new_props.append(new_prop)
   else:
     self.close()
     raise MissingParameterHTTPError(param_names=['real_props', 'fake_props'])
   return new_props
  def from_json(self, request, to_props=False):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, PolicyStatementModel.required)
    json_dict['__python_obj__'] = PolicyStatement.__module__+'.'+ PolicyStatement.__name__
    ps = json_serialize(json_dict)
    ps = json_deserialize(ps)

    if isinstance(ps, PolicyStatement):
      return ps
    else:
      self.close()
      raise MalformedJSONHTTPError()
示例#47
0
  def from_json(self, request, to_props=False):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, AssetAssociationModel.required)
    json_dict['__python_obj__'] = ClassAssociation.__module__+'.'+ClassAssociation.__name__
    assoc = json_serialize(json_dict)
    assoc = json_deserialize(assoc)

    if isinstance(assoc, ClassAssociation):
      return assoc
    else:
      self.close()
      raise MalformedJSONHTTPError()
示例#48
0
  def from_json(self, request, to_props=False):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, TemplateGoalModel.required)
    json_dict['__python_obj__'] = TemplateGoal.__module__+'.'+ TemplateGoal.__name__
    tg = json_serialize(json_dict)
    tg = json_deserialize(tg)

    if isinstance(tg, TemplateGoal):
      return tg
    else:
      self.close()
      raise MalformedJSONHTTPError()
示例#49
0
文件: TraceDAO.py 项目: failys/cairis
  def from_json(self, request):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, TraceModel.required)
    json_dict['__python_obj__'] = Trace.__module__+'.'+ Trace.__name__
    tr = json_serialize(json_dict)
    tr = json_deserialize(tr)

    if isinstance(tr, Trace):
      return tr
    else:
      self.close()
      raise MalformedJSONHTTPError()
示例#50
0
    def post(self):
        session_id = get_session_id(session, request)
        json_dict = request.get_json(silent=True)

        if json_dict is False or json_dict is None:
            raise MalformedJSONHTTPError(data=request.get_data())

        cimport_params = json_dict.get('object', None)
        check_required_keys(cimport_params or {}, CImportParams.required)
        file_contents = cimport_params['urlenc_file_contents']
        file_contents = unquote(file_contents)
        type = cimport_params['type']
        overwrite = cimport_params.get('overwrite', None)

        if file_contents.startswith('<?xml'):
            fd, abs_path = mkstemp(suffix='.xml')
            fs_temp = open(abs_path, 'w')
            fs_temp.write(file_contents)
            fs_temp.close()
            fd_close(fd)

            try:
                result = file_import(abs_path, type, overwrite, session_id=session_id)
            except DatabaseProxyException as ex:
                raise ARMHTTPError(ex)
            except ARMException as ex:
                raise ARMHTTPError(ex)
            except Exception as ex:
                raise CairisHTTPError(
                    status_code=500,
                    message=str(ex.message),
                    status='Unknown error'
                )

            remove_file(abs_path)

            resp_dict = {'message': str(result)}
            resp = make_response(json_serialize(resp_dict, session_id=session_id), httplib.OK)
            resp.headers['Content-Type'] = 'application/json'
            return resp
        else:
            raise CairisHTTPError(
                status_code=httplib.BAD_REQUEST,
                message='The provided file is not a valid XML file',
                status='Invalid XML input'
            )
示例#51
0
    def from_json(self, request):
        json = request.get_json(silent=True)
        if json is False or json is None:
            self.close()
            raise MalformedJSONHTTPError(data=request.get_data())

        json_dict = json['object']
        check_required_keys(json_dict, TraceModel.required)
        json_dict['__python_obj__'] = Trace.__module__ + '.' + Trace.__name__
        tr = json_serialize(json_dict)
        tr = json_deserialize(tr)

        if isinstance(tr, Trace):
            return tr
        else:
            self.close()
            raise MalformedJSONHTTPError()
示例#52
0
  def from_json(self, request, to_props=False):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, ValueTypeModel.required)
    json_dict['__python_obj__'] = ValueType.__module__+'.'+ ValueType.__name__
    vt = json_serialize(json_dict)
    vt = json_deserialize(vt)

    if isinstance(vt, ValueType):
      return vt 
    else:
      self.close()
      raise MalformedJSONHTTPError()
示例#53
0
  def convert_properties(self, real_props=None, fake_props=None):
    new_props = []
    if real_props is not None:
      for real_prop in real_props:
        assert isinstance(real_prop, ObstacleEnvironmentProperties)
        del real_prop.theLabel

        new_goal_refinements = []
        for gr in real_prop.theGoalRefinements:
          new_goal_refinements.append(RefinementModel(gr[0],gr[1],gr[2],gr[3],gr[4]))

        new_subgoal_refinements = []
        for sgr in real_prop.theSubGoalRefinements:
          new_subgoal_refinements.append(RefinementModel(sgr[0],sgr[1],sgr[2],sgr[3],sgr[4]))

        real_prop.theGoalRefinements = new_goal_refinements
        real_prop.theSubGoalRefinements = new_subgoal_refinements
        new_props.append(real_prop)
    elif fake_props is not None:
      for fake_prop in fake_props:
        check_required_keys(fake_prop, ObstacleEnvironmentPropertiesModel.required)

        new_goal_refinements = []
        for gr in fake_prop['theGoalRefinements']:
          new_goal_refinements.append((gr['theEndName'],gr['theEndType'],gr['theRefType'],gr['isAlternate'],gr['theRationale']))

        new_subgoal_refinements = []
        for sgr in fake_prop['theSubGoalRefinements']:
          new_subgoal_refinements.append((sgr['theEndName'],sgr['theEndType'],sgr['theRefType'],sgr['isAlternate'],sgr['theRationale']))

        new_prop = ObstacleEnvironmentProperties(
                   environmentName=fake_prop['theEnvironmentName'],
                   lbl='',
                   definition=fake_prop['theDefinition'],
                   category=fake_prop['theCategory'],
                   gRefs=new_goal_refinements,
                   sgRefs=new_subgoal_refinements,
                   concs=fake_prop['theConcerns'])
        new_prop.theProbability = fake_prop['theProbability']
        new_prop.theProbabilityRationale = fake_prop['theProbabilityRationale']
        new_props.append(new_prop)
    else:
      self.close()
      raise MissingParameterHTTPError(param_names=['real_props', 'fake_props'])

    return new_props
示例#54
0
  def type_from_json(self, request):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, ValueTypeModel.required)
    json_dict['__python_obj__'] = ValueType.__module__+'.'+ValueType.__name__

    value_type = json_serialize(json_dict)
    value_type = json_deserialize(value_type)
    if not isinstance(value_type, ValueType):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      return value_type
示例#55
0
  def from_json(self, request):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, DomainPropertyModel.required)
    json_dict['__python_obj__'] = DomainProperty.__module__ + '.' + DomainProperty.__name__

    domain_property = json_serialize(json_dict)
    domain_property = json_deserialize(domain_property)
    if not isinstance(domain_property, DomainProperty):
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())
    else:
      return domain_property
示例#56
0
  def from_json(self, request, to_props=False):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, ExternalDocumentModel.required)
    json_dict['__python_obj__'] = ExternalDocument.__module__+'.'+ ExternalDocument.__name__
    edoc = json_serialize(json_dict)
    edoc = json_deserialize(edoc)

    if isinstance(edoc, ExternalDocument):
      return edoc
    else:
      self.close()
      raise MalformedJSONHTTPError()
示例#57
0
  def from_json(self, request, to_props=False):
    json = request.get_json(silent=True)
    if json is False or json is None:
      self.close()
      raise MalformedJSONHTTPError(data=request.get_data())

    json_dict = json['object']
    check_required_keys(json_dict, PersonaCharacteristicModel.required)
    json_dict['__python_obj__'] = PersonaCharacteristic.__module__+'.'+ PersonaCharacteristic.__name__
    pc = json_serialize(json_dict)
    pc = json_deserialize(pc)
    pc,ps,rss,rcs = self.convert_pcrs(fake_pc=pc)

    if isinstance(pc, PersonaCharacteristic):
      return pc,ps,rss,rcs
    else:
      self.close()
      raise MalformedJSONHTTPError()