Skip to content

Commit

Permalink
feat: Fix parser
Browse files Browse the repository at this point in the history
  • Loading branch information
drorganvidez committed Oct 28, 2024
1 parent 81cfce4 commit 00dc40a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 46 deletions.
16 changes: 8 additions & 8 deletions app/modules/flamapy/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@
logger = logging.getLogger(__name__)


@flamapy_bp.route('/flamapy/check_uvl/<int:file_id>', methods=['GET'])
def check_uvl(file_id):
@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 = []
Expand All @@ -36,8 +40,7 @@ def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
self.errors.append(error_message)

try:
hubfile = HubfileService().get_by_id(file_id)
input_stream = FileStream(hubfile.get_path())
input_stream = FileStream(filepath)
lexer = UVLCustomLexer(input_stream)

error_listener = CustomErrorListener()
Expand All @@ -59,10 +62,7 @@ def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):

# After parsing, try transforming the model
try:
# Assuming some logic here like loading and validating the model
# This part should contain your logic for using the Flamapy transformation
FLAMAFeatureModel(hubfile.get_path()) # Example usage
# You can optionally print or process the model here
FLAMAFeatureModel(filepath) # Example usage
return jsonify({"message": "Valid Model"}), 200

except FlamaException as fe:
Expand Down
32 changes: 20 additions & 12 deletions app/modules/hubfile/assets/js/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,46 +33,55 @@ let dropzone = Dropzone.options.myDropzone = {
let ext = file.name.split('.').pop();
if (ext !== 'uvl') {
this.removeFile(file);

let alert = document.createElement('p');
alert.textContent = 'Invalid file extension: ' + file.name;
alerts.appendChild(alert);
alerts.style.display = 'block';
} else {
} else {
// Read the file as text to pass it to the UVL parser
let reader = new FileReader();
reader.onload = function(event) {
const fileContent = event.target.result; // This contains the UVL file content

// Now, use uvl-parser to parse the content
try {
const featureModel = new FeatureModel(fileContent);
const tree = featureModel.getFeatureModel(); // This is your parsed UVL tree

console.log("Parsed UVL Feature Model:", tree);
valid = true;



// You can now manipulate `tree` or display it in the UI as needed
} catch (error) {
if (error instanceof TypeError) {
console.error("Caught a TypeError:", error.message);
// Verificar si el error es debido a `Error.captureStackTrace`
if (error.message.includes("Error.captureStackTrace is not a function")) {
console.warn("Error.captureStackTrace is not supported in this environment.");
valid = false;
let alert = document.createElement('p');
alert.innerHTML = 'Syntax error in <b>' + file.name + '</b>';
alerts.appendChild(alert);
alerts.style.display = 'block';
} else {
// Si es un error de sintaxis en el UVL, mostrar mensaje personalizado
valid = false;
console.error("Error parsing UVL file:", error.message);
invalid_uvl_message = error.message
invalid_uvl_message = error.message;

// Muestra el mensaje de error de sintaxis en el UI
let alert = document.createElement('p');
alert.innerHTML = 'Syntax error in <b>' + file.name + '</b><br>&nbsp;>&nbsp;>&nbsp;>&nbsp;' + error.message;
alerts.appendChild(alert);
alerts.style.display = 'block';
}

}
};
reader.readAsText(file); // Read the file as text
}

});

this.on('error', function (file, response) {
console.error("Error uploading file: ", response);
let alert = document.createElement('p');
Expand All @@ -81,7 +90,6 @@ let dropzone = Dropzone.options.myDropzone = {
alerts.style.display = 'block';
});


this.on('success', function (file, response) {

if(valid){
Expand Down
52 changes: 26 additions & 26 deletions app/modules/hubfile/routes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from datetime import datetime
import os
import uuid
from flask import current_app, jsonify, make_response, request, send_from_directory
from flask import current_app, jsonify, make_response, request, send_from_directory, url_for
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 @@ -22,39 +23,38 @@ def upload_file():
if not file or not file.filename.endswith(".uvl"):
return jsonify({"message": "No valid file"}), 400

# create temp folder
# Crear carpeta temporal si no existe
if not os.path.exists(temp_folder):
os.makedirs(temp_folder)

file_path = os.path.join(temp_folder, file.filename)

if os.path.exists(file_path):
# Generate unique filename (by recursion)
base_name, extension = os.path.splitext(file.filename)
i = 1
while os.path.exists(
os.path.join(temp_folder, f"{base_name} ({i}){extension}")
):
i += 1
new_filename = f"{base_name} ({i}){extension}"
file_path = os.path.join(temp_folder, new_filename)
else:
new_filename = file.filename
# Ruta temporal para el archivo
temp_file_path = os.path.join(temp_folder, file.filename)

# Guardar temporalmente el archivo
try:
file.save(file_path)
file.save(temp_file_path)
except Exception as e:
return jsonify({"message": str(e)}), 500

return (
jsonify(
{
"message": "UVL uploaded and validated successfully",
"filename": new_filename,
}
),
200,
)
# 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

# Si el archivo es válido, guardarlo permanentemente
new_filename = file.filename
return jsonify(
{
"message": "UVL uploaded and validated successfully",
"filename": new_filename,
}
), 200


@hubfile_bp.route("/hubfile/delete", methods=["POST"])
Expand Down

0 comments on commit 00dc40a

Please sign in to comment.