def update_goal(problem_id, goal):
    """
    Update the existing goal value
    
    :param problem_id: The id of the problem being manipulated
    :type problem_id: int
    :param goal: Goal object that needs to be updated.
    :type goal: dict | bytes

    :rtype: None
    """
    #check if problem_id is positive
    if (problem_id < 0):
        return jsonify(Error(400, "Negative Problem_ID")), HTTP_405_BAD_REQUEST

    if connexion.request.is_json:
        #get JSON from response
        goal = connexion.request.get_json()

        #contact Storage
        params = "id=%s/" % str(problem_id)
        goal_url = storage_url + str(params)
        response = requests.get(goal_url)

        #check that Problem exists
        if (response.status_code == 404):
            return jsonify(Error(
                404, "Problem not found")), status.HTTP_404_NOT_FOUND

        #check if Storage died
        elif (response.status_code != 200):
            return jsonify(
                Error(500, "Storage server error: couldn't update goal")
            ), status.HTTP_500_INTERNAL_SERVER_ERROR

        version = response.json()["version"]
        #get problem from response
        problem = response.json()["body"]

        #check if start and goal are in valid range
        #if (abs(problem['goal']['coordinates']['latitude'] -  ) > 100):
        #    return jsonify(Error(405, "Goal is out of range.")), HTTP_405_INVALID_INPUT

        #store new Goal coordinates into Goal of Problem
        problem['goal']['coordinates'] = goal['coordinates']

        #PUT the new Problem back into Storage
        params = "id=%s/ver=%s" % (str(problem_id), str(version))
        goal_url = storage_url + str(params)
        put_response = requests.put(goal_url, json=problem)

        #check if Storage died
        if (response.status_code != 200):
            return jsonify(
                Error(500, "Storage server error: couldn't update goal")
            ), status.HTTP_500_INTERNAL_SERVER_ERROR

        return jsonify({"response": "Update successful"})

    #return an error if input isn't JSON
    return jsonify(
        Error(
            415,
            "Unsupported media type: Please submit data as application/json data"
        )), status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
Пример #2
0
def delete_robot(problem_id, robot_id, version):
    """
    Delete Robot
    This removes the robot by the given ID
    :param problem_id: The id of the problem being manipulated
    :type problem_id: int
    :param robot_id: The ID of the Obstacle that needs to be deleted.
    :type robot_id: int
    :param version: The version of the obstacle to be updated.
    :type version: float

    :rtype: None
    """
    #check if problem_id is positive
    if (problem_id < 0):
        return jsonify(Error(
            400, "Negative Problem_ID")), status.HTTP_400_BAD_REQUEST

    #check if robot_id is positive
    if (robot_id < 0):
        return jsonify(Error(400,
                             "Negative Robot_ID")), status.HTTP_400_BAD_REQUEST

    #contact Storage
    robot_url = storage_url + str(problem_id)
    response = requests.get(robot_url)

    #check if Problem exists
    if (response.status_code == 404):
        return jsonify(Error(404,
                             "Problem not found")), status.HTTP_404_NOT_FOUND

    #check if Storage died
    elif (response.status_code != 200):
        return jsonify(
            Error(500, "Storage server error: couldn't update Robot")
        ), status.HTTP_500_INTERNAL_SERVER_ERROR

    #get Problem from response
    problem = response.json()

    #make sure versions match
    if (version != problem["version"]):
        return jsonify(
            Error(409, ("Versions numbers do not match. Version should be %s",
                        str(problem['version'])))), status.HTTP_409_CONFLICT

    #get robots from Problem
    robots = problem["robots"]

    #make sure there isn't a Robot with the same ID
    if (not any(o_robot["id"] == robot_id for o_robot in robots)):
        return jsonify(Error(404,
                             "Robot not found")), status.HTTP_404_NOT_FOUND
    else:
        for robot in robots:
            if (robot["id"] == robot_id):
                robots.remove(robot)
        problem["robots"] = robots

    #update version number
    new_version = problem["version"]
    new_version = new_version + 1
    problem["version"] = new_version

    #PUT new Problem to Storage
    put_response = requests.put(robot_url, json=problem)

    #check if Storage died
    if (response.status_code != 200):
        return jsonify(
            Error(500, "Storage server error: couldn't add new robot")
        ), status.HTTP_500_INTERNAL_SERVER_ERROR

    #return response from Storage
    reply = {}
    reply["version"] = problem["version"]
    reply["response"] = put_response.json()
    return jsonify(reply)
Пример #3
0
def add_part(part):
    """
    add_part
    Creates a new part
    :param part: Part to add
    :type part: dict | bytes

    :rtype: Part
    """
    if connexion.request.is_json:
        part = PartNew.from_dict(connexion.request.get_json())

    try:
        fpart = deserialize_PartNew(part)
    except ControllerError as e:
        return e.error, 403

    fpart.save()

    fparameters = []
    if part.parameters:
        for parameter in part.parameters:
            fparameter = deserialize_PartParameter(parameter)
            fparameter.part = fpart
            fparameter.save()
            fparameters.append(fparameter)
        fpart.parameters.set(fparameters)


# TODO: enable bulk insert
    foffers = []
    if part.distributors:
        for part_distributor in part.distributors:
            try:
                fdistributor = api.models.Distributor.objects.get(
                    name=part_distributor.name)
            except:
                return Error(code=1000,
                             message='Distributor %s does not exists' %
                             part_distributor.name), 403
            for offer in part_distributor.offers:
                foffer = deserialize_PartOffer(offer)
                foffer.part = fpart
                foffer.distributor = fdistributor
                foffer.save()
                foffers.append(foffer)
        fpart.offers.set(foffers)

    fpart_manufacturers = []
    if part.manufacturers:
        for part_manufacturer in part.manufacturers:
            try:
                fmanufacturer = api.models.Manufacturer.objects.get(
                    name=part_manufacturer.name)
            except:
                return Error(code=1000,
                             message='Manufacturer %s does not exists' %
                             part_manufacturer.name), 403
            fpart_manufacturer = api.models.PartManufacturer()
            fpart_manufacturer.part = fpart
            fpart_manufacturer.manufacturer = fmanufacturer
            fpart_manufacturer.part_name = part_manufacturer.part_name
            fpart_manufacturer.save()
            fpart_manufacturers.append(fpart_manufacturer)
        fpart.manufacturers.set(fpart_manufacturers)

    fpart_storages = []
    if part.storages:
        for part_storage in part.storages:
            try:
                fstorage = api.models.Storage.objects.get(id=part_storage.id)
            except:
                return Error(code=1000,
                             message='Storage %s does not exists' %
                             part_storage.name), 403
            fpart_storage = api.models.PartStorage()
            fpart_storage.part = fpart
            fpart_storage.storage = fstorage
            fpart_storage.quantity = part_storage.quantity
            fpart_storage.save()
            fpart_storage.append(fpart_storage)
        fpart.storages.set(fpart_storages)

    fpart_attachements = []
    if part.attachements:
        for part_attachement in part.attachements:
            try:
                fattachement = api.models.File.objects.get(
                    id=part_attachement.id)
            except:
                return Error(code=1000,
                             message='File %s does not exists' %
                             part_attachement.id), 403
            fpart_attachement = api.models.PartAttachement()
            fpart_attachement.part = fpart
            fpart_attachement.file = fattachement
            fpart_attachement.description = part_attachement.description
            fpart_attachement.save()
            fpart_attachements.append(fpart_attachement)
        fpart.attachements.set(fpart_attachements)

    return serialize_Part(fpart)
Пример #4
0
def update_part(part_id, part):
    """
    update_part
    Update part
    :param part_id: Part id
    :type part_id: int
    :param part: Part to update
    :type part: dict | bytes

    :rtype: Part
    """
    if connexion.request.is_json:
        part = Part.from_dict(connexion.request.get_json())
    else:
        return Error(code=1000, message='Missing payload'), 403

    try:
        fpart = api.models.Part.objects.get(pk=part_id)
    except:
        return Error(code=1000,
                     message='Part %d does not exists' % part_id), 403

    try:
        fpart = deserialize_Part(part, fpart)
    except ControllerError as e:
        return e.error, 403

    fpart.save()

    fparameters = []
    if not part.parameters is None:
        # remove all parameters
        api.models.PartParameter.objects.filter(part=part_id).delete()
        # replace by interface ones
        for parameter in part.parameters:
            fparameter = deserialize_PartParameter(parameter)
            fparameter.part = fpart
            fparameter.save()
            fparameters.append(fparameter)
        fpart.parameters.set(fparameters)

    foffers = []
    if not part.distributors is None:
        # remove all part distributors
        api.models.PartOffer.objects.filter(part=part_id).delete()
        # import new values
        for part_distributor in part.distributors:
            try:
                fdistributor = api.models.Distributor.objects.get(
                    name=part_distributor.name)
            except:
                return Error(code=1000,
                             message='Distributor %s does not exists' %
                             part_distributor.name), 403

            for offer in part_distributor.offers:
                foffer = deserialize_PartOffer(offer)
                foffer.part = fpart
                foffer.distributor = fdistributor
                foffer.save()
                foffers.append(foffer)
        fpart.offers.set(foffers)

    fpart_manufacturers = []
    if not part.manufacturers is None:
        # remove all part distributors
        api.models.PartManufacturer.objects.filter(part=part_id).delete()
        # import new values
        for part_manufacturer in part.manufacturers:
            try:
                fmanufacturer = api.models.Manufacturer.objects.get(
                    name=part_manufacturer.name)
            except:
                return Error(code=1000,
                             message='Manufacturer %s does not exists' %
                             part_manufacturer.name), 403
            fpart_manufacturer = api.models.PartManufacturer()
            fpart_manufacturer.part = fpart
            fpart_manufacturer.manufacturer = fmanufacturer
            fpart_manufacturer.part_name = part_manufacturer.part_name
            fpart_manufacturer.save()
            fpart_manufacturers.append(fpart_manufacturer)
        fpart.manufacturers.set(fpart_manufacturers)

    fpart_storages = []
    if not part.storages is None:
        # remove all part distributors
        api.models.PartStorage.objects.filter(part=part_id).delete()
        # import new values
        for part_storage in part.storages:
            try:
                fstorage = api.models.Storage.objects.get(id=part_storage.id)
            except:
                return Error(code=1000,
                             message='Storage %s does not exists' %
                             part_storage.id), 403
            fpart_storage = api.models.PartStorage()
            fpart_storage.part = fpart
            fpart_storage.storage = fstorage
            fpart_storage.quantity = part_storage.quantity
            if fpart_storage.quantity < 0:
                fpart_storage.quantity = 0

            fpart_storage.save()
            fpart_storages.append(fpart_storage)
        fpart.storages.set(fpart_storages)

    fpart_attachements = []
    if not part.attachements is None:
        # remove all part distributors
        api.models.PartAttachement.objects.filter(part=part_id).delete()
        # import new values
        for part_attachement in part.attachements:
            try:
                fattachement = api.models.File.objects.get(
                    id=part_attachement.id)
            except:
                return Error(code=1000,
                             message='File %s does not exists' %
                             part_attachement.id), 403
            fpart_attachement = api.models.PartAttachement()
            fpart_attachement.part = fpart
            fpart_attachement.file = fattachement
            fpart_attachement.description = part_attachement.description
            fpart_attachement.save()
            fpart_attachements.append(fpart_attachement)
        fpart.attachements.set(fpart_attachements)

    return serialize_Part(fpart)
Пример #5
0
def get_path(problem_id):
    """
    Path
    Returns a description of the path from the robot&#39;s current location to the goal.
    :param problem_id: The id of the problem being manipulated
    :type problem_id: int

    :rtype: Path
    """
    #check if problem_id is positive
    if (problem_id < 0):
        return jsonify(Error(
            400, "Negative Problem_ID")), status.HTTP_400_BAD_REQUEST

    #Storage version control
    while True:
        #contact storage
        params = "id=%s/" % str(problem_id)
        path_url = storage_url + str(params)
        response = requests.get(path_url)

        #check that the Problem exists
        if (response.status_code == 404):
            return jsonify(Error(
                404, "Problem not found")), status.HTTP_404_NOT_FOUND

        #check if Storage died
        elif (response.status_code != 200):
            return jsonify(Error(
                500,
                "Storage server error")), status.HTTP_500_INTERNAL_SERVER_ERROR

        #get the Problem from the response
        problem = response.json()["body"]
        version = response.json()["version"]
        try:
            path = pathfind_from_json(problem, 1)
        except (ValueError, TypeError) as error:
            return jsonify(
                Error(
                    400,
                    "Incorrect problem structure: please check default problem",
                    str(error))), status.HTTP_400_BAD_REQUEST

        problem["path"] = path

        params = "id=%s/ver=%s/" % (str(problem_id), str(version))
        put_url = storage_url + str(params)
        response = requests.put(put_url, json=problem)

        if (response.status_code == 404):
            return jsonify(Error(
                404, "Problem not found")), status.HTTP_404_NOT_FOUND

        #check for Storage version control
        if (response.status_code != 412):
            #check if Storage died
            if (response.status_code != 200):
                return jsonify(Error(500, "Storage server error")
                               ), status.HTTP_500_INTERNAL_SERVER_ERROR
            break

    return jsonify(path)
Пример #6
0
def deserialize_PartNew(part, fpart=None):
    fpart = deserialize_PartData(part, fpart)
    if part.category:
        try:
            fpart.category = api.models.PartCategory.objects.get(
                pk=part.category.id)
        except:
            raise_on_error(
                Error(code=1000,
                      message='Category %d does not exists' %
                      part.category.id))
    else:
        fpart.category = None

    if part.footprint:
        try:
            fpart.footprint = api.models.VersionedFile.objects.get(
                pk=part.footprint.id)
        except:
            raise_on_error(
                Error(code=1000,
                      message='Footprint %d does not exists' %
                      part.footprint.id))
    else:
        fpart.footprint = None

    if part.symbol:
        try:
            fpart.symbol = api.models.VersionedFile.objects.get(
                pk=part.symbol.id)
        except:
            raise_on_error(
                Error(code=1000,
                      message='Symbol %d does not exists' % part.symbol.id))
    else:
        fpart.symbol = None

    if not part.childs is None:
        fchilds = []
        fchilds_check = []
        for child in part.childs:
            try:
                fchild = api.models.Part.objects.get(pk=child.id)
                fchilds.append(fchild)
                fchilds_check.append(fchild)
            except:
                raise_on_error(
                    Error(code=1000,
                          message='Part %d does not exists' % part.id))

        # recursive check
        while len(fchilds_check) > 0:
            fchild = fchilds_check.pop()
            if fchild.pk == part.id:
                raise_on_error(
                    Error(code=1000, message='Part cannot be child of itself'))
            for fchild in fchild.childs.all():
                fchilds_check.append(fchild)

        fpart.childs.set(fchilds)

    return fpart
Пример #7
0
def test_cpu_get():  # noqa: E501
    try:
        with open("/proc/cpuinfo", "r") as cpu:
            return cpu.read()
    except IOError as e:
        return Error("I/O error({0}): {1}".format(e.errno, e.strerror))
Пример #8
0
def check_id_post(image,
                  apiKey,
                  name=None,
                  birthdate=None,
                  mothername=None,
                  releasedate=None,
                  id_num=None,
                  birthplace=None,
                  runlevel=None):  # noqa: E501
    """Checks submitted information

    The endpoint checks the submitted information against the submitted image. # noqa: E501

    :param image:
    :type image: werkzeug.datastructures.FileStorage
    :param name:
    :type name: str
    :param birthdate:
    :type birthdate: str
    :param mothername:
    :type mothername: str
    :param releasedate:
    :type releasedate: str
    :param id_num:
    :type id_num: str
    :param birthplace:
    :type birthplace: str
    :param runlevel: Lower value means faster runtime, but lower precision.
    :type runlevel: int

    :rtype: CheckResponse
    """

    try:
        if apiKey not in content:
            return Error("Invalid ApiKey provided!")

        if runlevel is None:
            runlevel = 0

        img = __get_image_from_stream(image, runlevel)
        if type(img) is Error:
            return img

        validate_fields = {}
        if name is not None:
            validate_fields['name'] = name.strip()
        if birthdate is not None:
            validate_fields['birthdate'] = birthdate
        if mothername is not None:
            validate_fields['mother_name'] = mothername
        if releasedate is not None:
            validate_fields['release_date'] = releasedate
        if id_num is not None:
            validate_fields['id_number'] = id_num
        if birthplace is not None:
            validate_fields['birthplace'] = birthplace

        card = id_card.validate_id_card(img, runlevel, validate_fields)
        if type(card) is str:
            return Error(card)
        elif type(card) is not dict:
            return Error("Card not found.")
        else:

            if card['validation_failed']:
                result = 'reject'
            elif card['validation_success']:
                result = 'accept'
            else:
                result = 'validate'

            return CheckResponse(
                id_num=None if id_num is None else card['id_number'],
                birthdate=None if birthdate is None else card['birthdate'],
                name=None if name is None else card['name'],
                mother_name=None
                if mothername is None else card['mother_name'],
                release_date=None
                if releasedate is None else card['release_date'],
                birthplace=None if birthplace is None else card['birthplace'],
                validation_result=result)
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        app.logger.log(logging.ERROR,
                       ''.join('!! ' + line
                               for line in lines))  # Log it or whatever here
        return Error("Card not found.")
def update_obstacle(problem_id, obstacle_id, updated_obstacle=None):
    """
    Update an existing obstacle
    
    :param problem_id: The id of the problem being manipulated
    :type problem_id: int
    :param obstacle_id: The id of the obstacle to be updated.
    :type obstacle_id: int
    :param updated_obstacle: Obstacle object that needs to be added to the list.
    :type updated_obstacle: dict | bytes

    :rtype: None
    """
    updated_obstacle = Obstacle.from_dict(connexion.request.get_json())

    if (problem_id < 0):
        return jsonify(Error(400, "Negative Problem_ID")), status.HTTP_400_BAD_REQUEST

    #check if obstacle_id is positive
    if (obstacle_id < 0):
        return jsonify(Error(400, "Negative Obstacle_ID")), status.HTTP_400_BAD_REQUEST

    #check if input is JSON
    if connexion.request.is_json:
        #get JSON from input
        try:
            obstacle = Obstacle.from_dict(connexion.request.get_json())
        except (ValueError, BadRequest) as error:
            return jsonify(Error(400, "Validation error; please check inputs", str(error))), status.HTTP_400_BAD_REQUEST
        
        obstacle = connexion.request.get_json()

        while True:
            #contact Storage
            params = "id=%s/" % str(problem_id)
            obst_url = storage_url + str(params)
            response = requests.get(obst_url)
            
            #check if Problem exists
            if (response.status_code == 404):
                return jsonify(Error(404, "Problem not found")), status.HTTP_404_NOT_FOUND
            
            #check if Storage died
            elif (response.status_code != 200):
                return jsonify(Error(500, "Storage server error: couldn't update Obstacle")), status.HTTP_500_INTERNAL_SERVER_ERROR
            
            #get Problem from response
            problem = response.json()["body"]
            version = response.json()["version"]

            #get list of Obstacles from Problem
            obstacles = problem["obstacles"]

            #Go through list of Obstacles for a specific ID
            #if found, update coordinates and break loop
            changed = False;
            for o_obstacle in obstacles:
                if (o_obstacle["obstacle_id"] == obstacle_id):
                    obstacles.remove(o_obstacle)
                    obstacles.append(obstacle)
                    problem["obstacles"] = obstacles
                    changed = True
                    break

            #if no Obstacle was found, return error
            if(not changed):
                return jsonify(Error(404, "Obstacle not found")), status.HTTP_404_NOT_FOUND

            #PUT new Problem into Storage
            params = "id=%s/ver=%s/" % (str(problem_id), str(version))
            put_url = storage_url + str(params)
            put_response = requests.put(put_url, json=problem)

            if (response.status_code != 412):
                #check if Storage died
                if (response.status_code != 200):
                    return jsonify(Error(500, "Storage server error: couldn't update obstacle")), status.HTTP_500_INTERNAL_SERVER_ERROR
                break

        return jsonify({"message" : "Successfully updated"})
    
    #return Error if not JSON
    return jsonify(Error(415,"Unsupported media type: Please submit data as application/json data")), status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
def add_obstacle(problem_id, obstacle):
    """
    Add a new obstacle to the list
    
    :param problem_id: The id of the problem being manipulated
    :type problem_id: int
    :param obstacle: Obstacle object that needs to be added to the list.
    :type obstacle: dict | bytes

    :rtype: int
    """

    #check if problem_id is positive
    if (problem_id < 0):
        return jsonify(Error(400, "Negative Problem_ID")), status.HTTP_400_BAD_REQUEST

    #check if input is JSON
    if connexion.request.is_json:
        #get JSON from input
        try:
            obstacle = Obstacle.from_dict(connexion.request.get_json())
        except (ValueError, BadRequest) as error:
            return jsonify(Error(400, "Validation error; please check inputs", str(error))), status.HTTP_400_BAD_REQUEST

        obstacle = connexion.request.get_json()

        while True: 
            #contact Storage
            params = "id=%s/" % str(problem_id)
            obst_url = storage_url + str(params)
            response = requests.get(obst_url)
         
            #check if Problem exists
            if (response.status_code == 404):
                return jsonify(Error(404, "Problem not found")), status.HTTP_404_NOT_FOUND
            
            #check if Storage died
            elif (response.status_code != 200):
                return jsonify(Error(500, "Storage server error: couldn't add Obstacle")), status.HTTP_500_INTERNAL_SERVER_ERROR
            
            #get Problem from response
            problem = response.json()["body"]
            version = response.json()["version"]

            #get Obstacles from Problem
            obstacles = problem["obstacles"]

            #make sure there isn't an Obstacle with the same ID
            if (not any(o_obstacle["obstacle_id"] == obstacle["obstacle_id"] for o_obstacle in obstacles)):
                obstacles.append(obstacle)
                problem["obstacles"] = obstacles
            else:
                return jsonify(Error(409, "Obstacle ID already exists; this must be a unique value")), status.HTTP_409_CONFLICT

            #PUT new Problem to Storage
            params = "id=%s/ver=%s/" % (str(problem_id), str(version))
            put_url = storage_url + str(params)
            put_response = requests.put(put_url, json=problem)

            if (response.status_code != 412):
                #check if Storage died
                if (response.status_code != 200):
                    return jsonify(Error(500, "Storage server error: couldn't add Obstacle")), status.HTTP_500_INTERNAL_SERVER_ERROR
                break

        #return response from Storage
        return jsonify({"response":"Successfully updated"})
    
    #return error if not JSON
    return jsonify(Error(415,"Unsupported media type: Please submit data as application/json data")), status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
Пример #11
0
def interpretError(error):
    return Error(str(error), 400, "Bad request"), 400