Skip to content

Commit

Permalink
fix: Fix UVL validation in client and server side
Browse files Browse the repository at this point in the history
  • Loading branch information
drorganvidez committed Oct 28, 2024
1 parent 00dc40a commit 94c4290
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 94 deletions.
2 changes: 1 addition & 1 deletion app/modules/confirmemail/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from app import db


class Confirmemail(db.Model):
class Confirmemail():
id = db.Column(db.Integer, primary_key=True)
16 changes: 0 additions & 16 deletions app/modules/dataset/templates/dataset/view_dataset.html
Original file line number Diff line number Diff line change
Expand Up @@ -331,22 +331,6 @@ <h4 style="margin-bottom: 0px;"><span class="badge bg-dark">{{ dataset.count_fea
<i data-feather="eye"></i> View
</button>

<div class="btn-group" role="group">
<button id="btnGroupDrop{{ file.id }}" type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" style=" border-radius: 5px;">
<i data-feather="check"></i> Check
</button>
<ul class="dropdown-menu" aria-labelledby="btnGroupDrop{{ file.id }}">
<li>
<a class="dropdown-item" onclick="checkUVL('{{ file.id }}')">Syntax check</a>
</li>
<!--
<li>
<a class="dropdown-item" onclick="checkSAT('{{ file.id }}')">SAT validity check</a>
</li>
-->
</ul>
</div>

<button onclick="addToCart('{{ file.id }}')" class="btn btn-outline-secondary btn-sm" style="border-radius: 5px;">
<i data-feather="plus"></i> <i data-feather="download"></i> Add
</button>
Expand Down
5 changes: 5 additions & 0 deletions app/modules/flamapy/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from app import db


class Flamapy():
id = db.Column(db.Integer, primary_key=True)
65 changes: 0 additions & 65 deletions app/modules/flamapy/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,76 +2,11 @@
from app.modules.hubfile.services import HubfileService
from flask import send_file, jsonify
from app.modules.flamapy import flamapy_bp
from flamapy.interfaces.python.flamapy_feature_model import FLAMAFeatureModel
from flamapy.core.exceptions import FlamaException
import os

from antlr4 import CommonTokenStream, FileStream
from uvl.UVLCustomLexer import UVLCustomLexer
from uvl.UVLPythonParser import UVLPythonParser
from antlr4.error.ErrorListener import ErrorListener

logger = logging.getLogger(__name__)


@flamapy_bp.route('/flamapy/check_uvl', methods=['POST'])
def check_uvl():
# Obtener la ruta del archivo desde los datos de la solicitud
data = request.get_json()
filepath = data.get("filepath")

class CustomErrorListener(ErrorListener):
def __init__(self):
self.errors = []

def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
if "\\t" in msg:
warning_message = (
f"The UVL has the following warning that prevents reading it: "
f"Line {line}:{column} - {msg}"
)
print(warning_message)
self.errors.append(warning_message)
else:
error_message = (
f"The UVL has the following error that prevents reading it: "
f"Line {line}:{column} - {msg}"
)
self.errors.append(error_message)

try:
input_stream = FileStream(filepath)
lexer = UVLCustomLexer(input_stream)

error_listener = CustomErrorListener()

lexer.removeErrorListeners()
lexer.addErrorListener(error_listener)

stream = CommonTokenStream(lexer)
parser = UVLPythonParser(stream)

parser.removeErrorListeners()
parser.addErrorListener(error_listener)

# Optional: Commented out for now
# tree = parser.featureModel()

if error_listener.errors:
return jsonify({"errors": error_listener.errors}), 400

# After parsing, try transforming the model
try:
FLAMAFeatureModel(filepath) # Example usage
return jsonify({"message": "Valid Model"}), 200

except FlamaException as fe:
return jsonify({"error": f"Model transformation failed: {str(fe)}"}), 400

except Exception as e:
return jsonify({"error": str(e)}), 500


@flamapy_bp.route('/flamapy/valid/<int:file_id>', methods=['GET'])
def valid(file_id):
return jsonify({"success": True, "file_id": file_id})
Expand Down
56 changes: 56 additions & 0 deletions app/modules/flamapy/services.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,63 @@
from app.modules.flamapy.repositories import FlamapyRepository
from core.services.BaseService import BaseService
from flamapy.interfaces.python.flamapy_feature_model import FLAMAFeatureModel
from flamapy.core.exceptions import FlamaException

from antlr4 import CommonTokenStream, FileStream
from uvl.UVLCustomLexer import UVLCustomLexer
from uvl.UVLPythonParser import UVLPythonParser
from antlr4.error.ErrorListener import ErrorListener


class FlamapyService(BaseService):
def __init__(self):
super().__init__(FlamapyRepository())

def check_uvl(self, filepath: str):

class CustomErrorListener(ErrorListener):

def __init__(self):
self.errors = []

def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
if "\\t" in msg:
warning_message = (
f"The UVL has the following warning that prevents reading it: "
f"Line {line}:{column} - {msg}"
)
self.errors.append(warning_message)
else:
error_message = (
f"The UVL has the following error that prevents reading it: "
f"Line {line}:{column} - {msg}"
)
self.errors.append(error_message)

try:
input_stream = FileStream(filepath)
lexer = UVLCustomLexer(input_stream)

error_listener = CustomErrorListener()

lexer.removeErrorListeners()
lexer.addErrorListener(error_listener)

stream = CommonTokenStream(lexer)
parser = UVLPythonParser(stream)

parser.removeErrorListeners()
parser.addErrorListener(error_listener)

if error_listener.errors:
return {"errors": error_listener.errors}, 400

try:
FLAMAFeatureModel(filepath)
return {"message": "Valid Model"}, 200

except FlamaException as fe:
return {"error": f"Model transformation failed: {str(fe)}"}, 400

except Exception as e:
return {"error": str(e)}, 500
23 changes: 11 additions & 12 deletions app/modules/hubfile/routes.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from datetime import datetime
import os
import uuid
from flask import current_app, jsonify, make_response, request, send_from_directory, url_for
from app.modules.flamapy.services import FlamapyService
from flask import current_app, jsonify, make_response, request, send_from_directory
from flask_login import current_user, login_required
import requests
from app.modules.hubfile import hubfile_bp
from app.modules.hubfile.models import HubfileViewRecord
from app.modules.hubfile.services import HubfileDownloadRecordService, HubfileService
Expand All @@ -13,6 +13,8 @@

hubfile_download_record_service = HubfileDownloadRecordService()

flamapy_service = FlamapyService()


@hubfile_bp.route("/hubfile/upload", methods=["POST"])
@login_required
Expand All @@ -36,16 +38,13 @@ def upload_file():
except Exception as e:
return jsonify({"message": str(e)}), 500

# Llamar a la ruta de validación `check_uvl` con una petición interna
check_uvl_url = url_for('flamapy.check_uvl', _external=True)
try:
response = requests.post(check_uvl_url, json={"filepath": temp_file_path})
if response.status_code != 200:
# Si no es válido, eliminar el archivo temporal y retornar error
os.remove(temp_file_path)
return response.json(), response.status_code
except requests.RequestException as e:
return jsonify({"error": str(e)}), 500
# Llamar directamente a `check_uvl` pasando la ruta temporal del archivo
validation_result, status_code = flamapy_service.check_uvl(temp_file_path)

if status_code != 200:
# Si no es válido, eliminar el archivo temporal y retornar error
os.remove(temp_file_path)
return jsonify(validation_result), status_code

# Si el archivo es válido, guardarlo permanentemente
new_filename = file.filename
Expand Down

0 comments on commit 94c4290

Please sign in to comment.