Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor and add ConversionConfig class as argument to createDcat #24

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions src/main/java/se/ams/dcatprocessor/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,9 @@ public static void main(String[] args) {

public static void convertFile(String filename) {
Manager manager = new Manager();
Path path = Path.of(filename);
MultiValuedMap<String, String> apiSpecMap = new ArrayListValuedHashMap<>();
String result;

try {
String content = Files.readString(path);
apiSpecMap.put(path.toString(), content);
result = manager.createDcat(apiSpecMap);
ConversionConfig config = ConversionConfig.fromFile(Path.of(filename));
String result = manager.createDcat(config);
assertTrue(!result.isEmpty());
System.out.println(result);
} catch (Exception e) {
Expand Down
121 changes: 121 additions & 0 deletions src/main/java/se/ams/dcatprocessor/ConversionConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
* This file is part of dcat-ap-se-processor.
*
* dcat-ap-se-processor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dcat-ap-se-processor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with dcat-ap-se-processor. If not, see <https://www.gnu.org/licenses/>.
*/

package se.ams.dcatprocessor;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Scanner;
import java.nio.charset.StandardCharsets;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.springframework.web.multipart.MultipartFile;


public class ConversionConfig {
private Path workDir;
private MultiValuedMap<String, String> apiSpecMap;

public static Path getDefaultWorkDir() {
return Path.of(System.getProperty("user.dir"));
}

public boolean isValid() {
return apiSpecMap != null && !apiSpecMap.isEmpty();
}

private ConversionConfig(MultiValuedMap<String, String> apiSpecMap, Path workDir) {
this.apiSpecMap = apiSpecMap;
this.workDir = workDir;
}

private ConversionConfig copy() {
return new ConversionConfig(apiSpecMap, workDir);
}

public ConversionConfig withWorkDir(Path workDir) {
ConversionConfig dst = copy();
dst.workDir = workDir;
return dst;
}

public MultiValuedMap<String, String> getApiSpecMap() {
assert(isValid());
return apiSpecMap;
}

public static ConversionConfig fromApiSpecMap(MultiValuedMap<String, String> apiSpecMap) {
return new ConversionConfig(apiSpecMap, getDefaultWorkDir());
}

public static ConversionConfig fromKeyValue(String key, String value) {
MultiValuedMap<String, String> apiSpecMap = new ArrayListValuedHashMap<>();
apiSpecMap.put(key, value);
return ConversionConfig.fromApiSpecMap(apiSpecMap);
}

public static ConversionConfig fromFile(Path path) throws IOException {
return ConversionConfig.fromKeyValue(path.toString(), Files.readString(path));
}

public static ConversionConfig fromDirectory(Path dir) throws IOException {
MultiValuedMap<String, String> apiSpecMap = new ArrayListValuedHashMap<>();

// returns pathnames for files and directory
File[] files = dir.toFile().listFiles((dir1, name) -> name.endsWith(".raml") || name.endsWith(".yaml") || name.endsWith(".json"));

// for each file in file array
if (files != null && files.length > 0) {
for (File file : files) {
Path path = Path.of(String.valueOf(file));
try {
String content = Files.readString(path);
apiSpecMap.put(path.toString(), content);
} finally {
}
}
}
return ConversionConfig.fromApiSpecMap(apiSpecMap);
}

public static ConversionConfig fromList(List<MultipartFile> apiFiles, List<Result> outResults) {
MultiValuedMap<String, String> apiSpecMap = new ArrayListValuedHashMap<>();
for (MultipartFile apiFile : apiFiles) {
if (!apiFile.isEmpty()) {
String apiSpecificationFromFile;
Scanner scanner;
try {
scanner = new Scanner(apiFile.getInputStream(), StandardCharsets.UTF_8.name());
apiSpecificationFromFile = scanner.useDelimiter("\\A").next();
scanner.close();
apiSpecMap.put(apiFile.getOriginalFilename(), apiSpecificationFromFile);
} catch (Exception e) { //Catch and show processing errors in web-gui
outResults.add(new Result(null, e.getMessage()));
e.printStackTrace();
}
}
}
return ConversionConfig.fromApiSpecMap(apiSpecMap);
}

public Path getWorkDir() {
return workDir;
}
}
67 changes: 15 additions & 52 deletions src/main/java/se/ams/dcatprocessor/Manager.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,61 +51,19 @@ public class Manager {
RDFWorker rdfWorker = new RDFWorker();

public String createDcatFromDirectory(String dir) throws Exception {
// create new file
File f = new File(dir);
String result = "Hittade inga filer";

MultiValuedMap<String, String> apiSpecMap = new ArrayListValuedHashMap<>();

// returns pathnames for files and directory
File[] files = f.listFiles((dir1, name) -> name.endsWith(".raml") || name.endsWith(".yaml") || name.endsWith(".json"));

// for each file in file array
if (files != null && files.length > 0) {
for (File file : files) {
Path path = Path.of(String.valueOf(file));
try {
String content = Files.readString(path);
apiSpecMap.put(path.toString(), content);
} finally {
}
}
result = this.createDcat(apiSpecMap);
}
return result;
ConversionConfig config = ConversionConfig.fromDirectory(Path.of(dir));
return config.isValid()? this.createDcat(config) : "Hittade inga filer";
}

public List<Result> createFromList(List<MultipartFile> apiFiles, Model model) {
List<Result> results = new ArrayList<>();
MultiValuedMap<String, String> apiSpecMap = new ArrayListValuedHashMap<>();
String result;

/* Generate DCAT-AP-SE from file */
for (MultipartFile apiFile : apiFiles) {
if (!apiFile.isEmpty()) {
String apiSpecificationFromFile;
Scanner scanner;
try {
scanner = new Scanner(apiFile.getInputStream(), StandardCharsets.UTF_8.name());
apiSpecificationFromFile = scanner.useDelimiter("\\A").next();
scanner.close();
apiSpecMap.put(apiFile.getOriginalFilename(), apiSpecificationFromFile);
} catch (Exception e) { //Catch and show processing errors in web-gui
result = e.getMessage();
results.add(new Result(null, result));
e.printStackTrace();
}
}
}
ConversionConfig config = ConversionConfig.fromList(apiFiles, results);
try {
result = createDcat(apiSpecMap);
results.add(new Result(null, createDcat(config)));
} catch (Exception e) {
result = e.getMessage();
results.add(new Result(null, result));
results.add(new Result(null, e.getMessage()));
e.printStackTrace();
}
results.add(new Result(null, result));
Copy link
Author

@jonasseglare jonasseglare May 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the description of the PR, I mentioned a bug that I fixed: In case we enter the catch branch above, then the same exception message is going to be pushed a second time to results because of this line. That is probably not what we want.

The updated code should address that issue.


model.addAttribute("results", results);
return results;
}
Expand All @@ -121,16 +79,21 @@ private void printToFile(String string, String fileName) throws Exception {
}

public String createDcat(MultiValuedMap<String, String> apiSpecMap) throws Exception {
return createDcat(ConversionConfig.fromApiSpecMap(apiSpecMap));
}

public String createDcat(ConversionConfig config) throws Exception {
ConverterCatalog catalogConverter = new ConverterCatalog();

HashMap<String, String> exceptions = new HashMap<>();
Map<String, List<ValidationError>> validationErrorsPerFileMap = new HashMap<>();
MultiValuedMap<String, String> apiSpecMap = config.getApiSpecMap();

String result = "Kunde inte generera en dcat fil";

for (String apiFileName : apiSpecMap.keySet()) {
Collection<String> api = apiSpecMap.get(apiFileName);
for (String apiSpecString : api) {
JSONObject jsonObjectFile = ApiDefinitionParser.getApiJsonString(apiSpecString);
JSONObject jsonObjectFile = ApiDefinitionParser.getApiJsonString(
apiSpecString, config.getWorkDir().resolve("output.json"));

// Creates both Catalog and other spec from the same file
if (apiSpecMap.size() == 1) {
Expand Down Expand Up @@ -212,8 +175,8 @@ public String createDcat(MultiValuedMap<String, String> apiSpecMap) throws Excep
return "There are Errors in the following files: \n" + exceptionResult;
}
if (result.contains("RDF")) {
printToFile(result, "dcat.rdf");
printToFile(result, config.getWorkDir().resolve("dcat.rdf").toString());
}
return result;
}
}
}
20 changes: 13 additions & 7 deletions src/main/java/se/ams/dcatprocessor/parser/ApiDefinitionParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,18 @@
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.nio.file.Path;

public class ApiDefinitionParser {

private static Logger logger = LoggerFactory.getLogger(ApiDefinitionParser.class);

public static JSONObject getApiJsonString(String fileString) throws IOException, ParseException {
// TODO: Do we need to provide a method with this signature for the sake of not breaking the API? Or will people adapt?
//
// public static JSONObject getApiJsonString(String fileString) throws IOException, ParseException

public static JSONObject getApiJsonString(
String fileString, Path outJsonFile) throws IOException, ParseException {
JSONParser parser = new JSONParser();
Stream<String> lines;
String apiJsonString = "";
Expand All @@ -47,9 +53,9 @@ public static JSONObject getApiJsonString(String fileString) throws IOException,
String apiLine1 = lines.limit(1).collect(Collectors.joining("\n"));

if (apiLine1.contains("openapi")) {
apiJsonString = getFileApiYamlRaml(fileString);
apiJsonString = getFileApiYamlRaml(fileString, outJsonFile);
} else if (apiLine1.contains("RAML")) {
apiJsonString = getFileApiYamlRaml(fileString);
apiJsonString = getFileApiYamlRaml(fileString, outJsonFile);
} else if (apiLine1.contains("{")){
apiJsonString = fileString;
}
Expand All @@ -64,8 +70,8 @@ public static JSONObject getApiJsonString(String fileString) throws IOException,
return jsonObjectFile;
}

private static String getFileApiYamlRaml(String apiSpec) throws IOException {
FileOutputStream output = new FileOutputStream("output.json");
private static String getFileApiYamlRaml(String apiSpec, Path outJsonFile) throws IOException {
FileOutputStream output = new FileOutputStream(outJsonFile.toFile());
JsonFactory factory = new JsonFactory();
JsonGenerator generator = factory.createGenerator(output, JsonEncoding.UTF8);

Expand All @@ -78,7 +84,7 @@ private static String getFileApiYamlRaml(String apiSpec) throws IOException {
output.close();

JSONParser jsonParser = new JSONParser();
FileReader reader = new FileReader("output.json");
FileReader reader = new FileReader(outJsonFile.toFile());

//Read JSON file
Object obj = jsonParser.parse(reader);
Expand Down Expand Up @@ -126,4 +132,4 @@ private static void build(Node yaml, JsonGenerator generator) throws IOException
}
}
}
}
}
95 changes: 95 additions & 0 deletions src/test/java/se/ams/dcatprocessor/ConversionConfigTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* This file is part of dcat-ap-se-processor.
*
* dcat-ap-se-processor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dcat-ap-se-processor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with dcat-ap-se-processor. If not, see <https://www.gnu.org/licenses/>.
*/

package se.ams.dcatprocessor;

import org.junit.jupiter.api.Test;
import org.apache.commons.collections4.MultiValuedMap;
import se.ams.dcatprocessor.rdf.DcatException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import org.springframework.mock.web.MockMultipartFile;
import java.nio.charset.StandardCharsets;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

public class ConversionConfigTest {

@Test
void testFromKeyValue() throws Exception {
ConversionConfig cfg = ConversionConfig.fromKeyValue("k119", "the spec goes here");
assertEquals(ConversionConfig.getDefaultWorkDir(), cfg.getWorkDir());
assertTrue(cfg.isValid());
MultiValuedMap m = cfg.getApiSpecMap();
assertEquals(1, m.size());
assertEquals(List.of("the spec goes here"), m.get("k119"));
checkWorkDirChangeIsWorking(cfg);
}

@Test
void testFromFileAndDirectory() throws Exception {
ConversionConfig[] configsToTest = new ConversionConfig[]{
ConversionConfig.fromFile(Path.of("src/test/resources/apidef/json_oas/obl_rek_oas.json")),
ConversionConfig.fromDirectory(Path.of("src/test/resources/apidef/json_oas")),
};
for (ConversionConfig cfg: configsToTest) {
checkJsonOasContents(cfg);
checkWorkDirChangeIsWorking(cfg);
}
}

@Test
void testMultipartFile() throws Exception {
String filename = "src/test/resources/apidef/json_oas/obl_rek_oas.json";
Path srcPath = Path.of(filename);
byte[] bytes = Files.readAllBytes(srcPath);
MockMultipartFile file = new MockMultipartFile(filename, filename, StandardCharsets.UTF_8.name(), bytes);

ArrayList<Result> results = new ArrayList<Result>();
ConversionConfig cfg = ConversionConfig.fromList(List.of(file), results);
checkJsonOasContents(cfg);

// If no exceptions are thrown, then nothing is pushed to results.
assertTrue(results.isEmpty());

checkWorkDirChangeIsWorking(cfg);
}

// Common checks for the unit tests
private ConversionConfig checkWorkDirChangeIsWorking(ConversionConfig src) throws Exception {
Path tempDir = Files.createTempDirectory("DCAT_workdir");
ConversionConfig dst = src.withWorkDir(tempDir);
assertEquals(tempDir, dst.getWorkDir());
assertEquals(ConversionConfig.getDefaultWorkDir(), src.getWorkDir());
return dst;
}

private void checkJsonOasContents(ConversionConfig cfg) {
assertTrue(cfg.isValid());
MultiValuedMap m = cfg.getApiSpecMap();
assertEquals(1, m.size());
Collection<String> coll = m.get("src/test/resources/apidef/json_oas/obl_rek_oas.json");
assertEquals(1, coll.size());
String first = coll.iterator().next();
assertTrue(first.startsWith("{"));
}
}
Loading