Commit d15c5357 authored by Philip Makedonski's avatar Philip Makedonski
Browse files

* minor refinements

parent e078ec1f
Loading
Loading
Loading
Loading
+30 −60
Original line number Diff line number Diff line
@@ -5,6 +5,8 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;

import de.ugoe.cs.swe.common.logging.LoggingInterface.LogLevel;

public class HttpFileClient {
    
    private static final String CRLF = "\r\n";
@@ -43,13 +45,13 @@ public class HttpFileClient {
     */
    public static ApiResponse uploadFiles(String url, Map<String, Path> files, 
                                         Map<String, String> additionalFields) throws IOException {
        System.out.println("CLIENT: Starting upload to " + url);
        log("CLIENT: Starting upload to " + url);
        URL apiUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
        
        try {
            // Configure connection
            System.out.println("CLIENT: Configuring connection");
            log("CLIENT: Configuring connection");
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
@@ -59,41 +61,41 @@ public class HttpFileClient {
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setChunkedStreamingMode(8192); // Use chunked mode to avoid hanging
            
            System.out.println("CLIENT: Getting output stream");
            log("CLIENT: Getting output stream");
            // Write multipart request body
            try (OutputStream out = conn.getOutputStream()) {
                System.out.println("CLIENT: Got output stream, writing data");
                log("CLIENT: Got output stream, writing data");
                
                // Add additional text fields if provided
                if (additionalFields != null) {
                    for (Map.Entry<String, String> field : additionalFields.entrySet()) {
                        System.out.println("CLIENT: Writing field: " + field.getKey());
                        log("CLIENT: Writing field: " + field.getKey());
                        writeField(out, field.getKey(), field.getValue());
                    }
                }
                
                // Add files
                for (Map.Entry<String, Path> file : files.entrySet()) {
                    System.out.println("CLIENT: Writing file: " + file.getValue().getFileName());
                    log("CLIENT: Writing file: " + file.getValue().getFileName());
                    writeFile(out, file.getKey(), file.getValue());
                }
                
                // End multipart request
                System.out.println("CLIENT: Writing end boundary");
                log("CLIENT: Writing end boundary");
                String endBoundary = "--" + BOUNDARY + "--" + CRLF;
                out.write(endBoundary.getBytes(StandardCharsets.UTF_8));
                out.flush();
                System.out.println("CLIENT: Finished writing request body");
                log("CLIENT: Finished writing request body");
            }
            
            // Read response
            System.out.println("CLIENT: Getting response code");
            log("CLIENT: Getting response code");
            int statusCode = conn.getResponseCode();
            System.out.println("CLIENT: Response code: " + statusCode);
            log("CLIENT: Response code: " + statusCode);
            InputStream responseStream = statusCode >= 400 ? conn.getErrorStream() : conn.getInputStream();
            
            String jsonResponse = readInputStream(responseStream);
//            System.out.println("CLIENT: Got response: " + jsonResponse);
//            log("CLIENT: Got response: " + jsonResponse);
            Map<String, List<String>> headers = conn.getHeaderFields();
            
            return new ApiResponse(jsonResponse, statusCode, headers);
@@ -168,46 +170,7 @@ public class HttpFileClient {
        }
    }
    
//    // Example usage
//    public static void main(String[] args) {
//        try {
//            // Example 1: Upload single file
//            Path file1 = Paths.get("document.pdf");
//            ApiResponse response1 = uploadFile(
//                "https://api.example.com/upload",
//                "file",
//                file1
//            );
//            
//            System.out.println("Status: " + response1.getStatusCode());
//            System.out.println("JSON Response: " + response1.getJsonBody());
//            System.out.println("Content-Type: " + response1.getHeader("Content-Type"));
//            
//            // Example 2: Upload multiple files with additional fields
//            Map<String, Path> files = new HashMap<>();
//            files.put("document", Paths.get("file1.pdf"));
//            files.put("image", Paths.get("photo.jpg"));
//            
//            Map<String, String> fields = new HashMap<>();
//            fields.put("userId", "12345");
//            fields.put("category", "reports");
//            
//            ApiResponse response2 = uploadFiles(
//                "https://api.example.com/upload",
//                files,
//                fields
//            );
//            
//            System.out.println("\nMultiple files uploaded:");
//            System.out.println("Status: " + response2.getStatusCode());
//            System.out.println("Response: " + response2.getJsonBody());
//            
//        } catch (IOException e) {
//            System.err.println("Upload failed: " + e.getMessage());
//            e.printStackTrace();
//        }
//    }
//}   

    // Example usage
    public static void main(String[] args) {
        try {
@@ -219,9 +182,9 @@ public class HttpFileClient {
//                file1
//            );
//            
//            System.out.println("Status: " + response1.getStatusCode());
//            System.out.println("JSON Response: " + response1.getJsonBody());
//            System.out.println("Content-Type: " + response1.getHeader("Content-Type"));
//            log("Status: " + response1.getStatusCode());
//            log("JSON Response: " + response1.getJsonBody());
//            log("Content-Type: " + response1.getHeader("Content-Type"));

            // Example 2: Upload multiple files with additional fields
            Map<String, Path> files = new HashMap<>();
@@ -230,8 +193,9 @@ public class HttpFileClient {
            
            
            Map<String, String> fields = new HashMap<>();
            fields.put("userId", "12345");
            fields.put("category", "reports");
            fields.put("backend", "titan");
            fields.put("command", "compiler");
            fields.put("target", "ttcn-3");
            
            ApiResponse response2 = uploadFiles(
                "http://localhost:3005/compile_asn",
@@ -239,13 +203,19 @@ public class HttpFileClient {
                fields
            );
            
            System.out.println("\nMultiple files uploaded:");
            System.out.println("Status: " + response2.getStatusCode());
            System.out.println("Response: " + response2.getJsonBody());
            log("\nMultiple files uploaded:");
            log("Status: " + response2.getStatusCode());
            log("Response: " + response2.getJsonBody());
            
        } catch (IOException e) {
            System.err.println("Upload failed: " + e.getMessage());
            log("ERROR: Upload failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    public static void log(String message) {
    	if (T3Q.getLogLevel() == LogLevel.DEBUG) {
    		System.out.println(message);
    	}
    }
}
 No newline at end of file
+7 −1
Original line number Diff line number Diff line
@@ -408,8 +408,15 @@ public class HttpFileServer {
            this.workDir = workDir;
        }
        
        
        
        @Override
        public Path process(Map<String, Path> files, Map<String, String> fields) throws Exception {
            String jsonFile = "asn.json";
            //TODO: this should be used instead, needs adaptation for logging output in case
//    		JsonSchemaBridge bridge = new JsonSchemaBridge();
//    		bridge.convertASN1toJSONSchemaLocal(command, files.values().stream().map(Path::toString).toList(), jsonFile);
        	
            // Build command with file paths as arguments
            List<String> cmd = new ArrayList<>();
            cmd.add(command);
@@ -419,7 +426,6 @@ public class HttpFileServer {
                cmd.add(file.toString());
            }
            cmd.add("-");
            String jsonFile = "asn.json";
			cmd.add(jsonFile);
            
			System.out.println("SERVER: Running "+cmd);
+32 −26
Original line number Diff line number Diff line
@@ -24,10 +24,11 @@ import de.ugoe.cs.swe.common.logging.LoggingInterface.LogLevel;

public class JsonSchemaBridge {
	StringBuilder ttcn = new StringBuilder();

	boolean logStructure = false;
	public JsonSchemaBridge() {
	}
	
	
	public void convertASN1toJSONSchema(String titanCompilerPath, List<String> asnFilePaths, String targetPath) {
		if (titanCompilerPath.startsWith("http")) {
			convertASN1toJSONSchemaRemote(titanCompilerPath, asnFilePaths, targetPath);
@@ -46,8 +47,9 @@ public class JsonSchemaBridge {
        }
        
        Map<String, String> fields = new HashMap<>();
        fields.put("command", "12345");
        fields.put("argument", "reports");
        fields.put("backend", "titan");
        fields.put("command", "compiler");
        fields.put("target", "ttcn-3");
        
        try {
        	ApiResponse response = HttpFileClient.uploadFiles(
@@ -55,8 +57,8 @@ public class JsonSchemaBridge {
        			files,
        			fields
        			);
        	System.out.println("\nASN.1 files submitted..:");
        	System.out.println("Status: " + response.getStatusCode());
        	log("\nASN.1 files submitted..:");
        	log("Status: " + response.getStatusCode());
        	String body = response.getJsonBody();
//        	System.out.println("Response: " + body);
        	Files.writeString(Path.of(targetPath), body, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
@@ -81,7 +83,7 @@ public class JsonSchemaBridge {
	        command.add(targetPath);
	        ProcessBuilder processBuilder = new ProcessBuilder(command);
	        if (T3Q.getLogLevel() == LogLevel.DEBUG) {
	        	System.out.println("Running Compiler: "+String.join(" ", command));
	        	log("Running Compiler: "+String.join(" ", command));
	        }
	        processBuilder.redirectErrorStream(true);

@@ -89,7 +91,7 @@ public class JsonSchemaBridge {
	        try (InputStream inputStream = process.getInputStream()) {
	            byte[] output = inputStream.readAllBytes();
		        if (T3Q.getLogLevel() == LogLevel.DEBUG) {
		        	System.out.println("Titan Compiler output: \n" + new String(output).replaceAll("\n", "\nTITAN: "));
		        	log("Titan Compiler output: \n" + new String(output).replaceAll("\n", "\nTITAN: "));
		        }
	        }

@@ -111,26 +113,32 @@ public class JsonSchemaBridge {
//		System.out.print(s);
		ttcn.append(s);
	}
	private void log(String s) {
//		System.out.println(s);
	private void log(String message) {
    	if (T3Q.getLogLevel() == LogLevel.DEBUG) {
    		System.out.println(message);
    	}
	}
	private void logStructure(String message) {
		if (logStructure) {
			System.out.println(message);
		}
	}	
	
	
	public void process(String path) throws Exception {
		JsonElement jsonElement = JsonParser.parseReader(new FileReader(path));
//        dumpJson("", jsonElement);
        //TODO: build reference map
		//TODO: break down and process recursively
        log("");
        logStructure("");
        int definitionsCount = 0;
        for (var d : jsonElement.getAsJsonObject().get("definitions").getAsJsonObject().entrySet()) {
        	//module
        	log(d.getKey());
        	logStructure(d.getKey());
        	//TODO: split across files?
        	append("module "+d.getKey()+" {\n"); 
            for (var e : d.getValue().getAsJsonObject().entrySet()) {
            	//type / object
            	log("  "+e.getKey());
            	logStructure("  "+e.getKey());
            	//TODO: check for others?
            	processObject(e.getKey(), e.getValue().getAsJsonObject(), "  ", false);
            	append("\n\n");
@@ -143,9 +151,7 @@ public class JsonSchemaBridge {
//        System.out.println(ttcn);
        Files.writeString(Path.of(path+".ttcn"), ttcn, 
        		StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
        if (T3Q.getLogLevel() == LogLevel.DEBUG) {
        	System.out.println("Converted "+definitionsCount+" definitions");
        }
        logStructure("Converted "+definitionsCount+" definitions");
	}
	
	private boolean isOptional(JsonObject o) {
@@ -177,7 +183,7 @@ public class JsonSchemaBridge {
				processArray(name, o, prefix);
			} else if (type.equals("null")) {
				//optional alternative?
    			log(prefix+"  OPTIONAL?");
				logStructure(prefix+"  OPTIONAL?");
    			append("anytype ");
			} else if (o.get("type").isJsonPrimitive()) {
				processPrimitive(name, o, prefix, type);
@@ -190,7 +196,7 @@ public class JsonSchemaBridge {
	private void processPrimitive(String name, JsonObject o, String prefix, String type) {
		//primitives: handle
		var subType = o.get("subType");
		log(prefix+"  PRIMITIVE: "+type);
		logStructure(prefix+"  PRIMITIVE: "+type);
		if (subType==null) {
			subType = new JsonPrimitive(type);
		}
@@ -241,7 +247,7 @@ public class JsonSchemaBridge {
	private void processStructured(String name, JsonObject o, String prefix, boolean skipBraces) {
		//fields
		var subType = o.get("subType");
		log(prefix+"->[object:"+subType+"]");
		logStructure(prefix+"->[object:"+subType+"]");
		preamble(name, prefix, subType);
		if (!skipBraces) {
			append("{\n");
@@ -249,7 +255,7 @@ public class JsonSchemaBridge {
		JsonObject props = o.get("properties").getAsJsonObject();
		var pi = 1;
		for (var p : props.entrySet()) {
			log(prefix+"  "+p.getKey());
			logStructure(prefix+"  "+p.getKey());
			JsonObject pDescription = p.getValue().getAsJsonObject();
			append(prefix+"  ");
			processObject(null, pDescription, prefix+"  ", false);
@@ -277,7 +283,7 @@ public class JsonSchemaBridge {
			refName = refName.substring(1);
		}
		//TODO: conflicts?
		log(prefix+"->[ref] "+refName+" : "+o.get("$ref").getAsString());
		logStructure(prefix+"->[ref] "+refName+" : "+o.get("$ref").getAsString());
		//TODO: some weird references generated by titan...
//			preamble(name, prefix, null);
		if (name!=null) {
@@ -295,7 +301,7 @@ public class JsonSchemaBridge {

	private void processEnum(String name, JsonObject o, String prefix) {
		//TODO: handle enums
		log(prefix+"->[enum]");
		logStructure(prefix+"->[enum]");
		for (var en : o.get("enum").getAsJsonArray()) {
			log(prefix+"  "+en.getAsString());
		}
@@ -323,7 +329,7 @@ public class JsonSchemaBridge {
	}

	private void processAnyOf(String name, JsonObject o, String prefix) {
		log(prefix+"->[union]");
		logStructure(prefix+"->[union]");
		if (isOptional(o)) {
			var opt = o.get("anyOf").getAsJsonArray().get(1).getAsJsonObject();
			processObject(null, opt, prefix+"  ", false);
@@ -368,8 +374,8 @@ public class JsonSchemaBridge {

    //for reference and debugging
	private void dumpJson(String prefix, Map.Entry<String,JsonElement> e) {
	    log("");
	    System.out.print(prefix+"  "+e.getKey() + ":");
		logStructure("");
	    logStructure(prefix+"  "+e.getKey() + ":");
	    dumpJson(prefix + "  ", e.getValue());
	}
	
@@ -380,7 +386,7 @@ public class JsonSchemaBridge {
	    } else if (e.isJsonObject()) {
	        ((JsonObject) e).entrySet().forEach(a -> dumpJson(prefix + "  ", a));
	    } else if (e.isJsonPrimitive()) {
	        System.out.print("  "+e);
	        logStructure("  "+e);
	    }
	}