Search in sources :

Example 11 with MolgenisException

use of org.molgenis.emx2.MolgenisException in project molgenis-emx2 by molgenis.

the class ExcelApi method getExcelTable.

static String getExcelTable(Request request, Response response) throws IOException {
    Table table = getTable(request);
    if (table == null)
        throw new MolgenisException("Table " + request.params(TABLE) + " unknown");
    Path tempDir = Files.createTempDirectory(MolgenisWebservice.TEMPFILES_DELETE_ON_EXIT);
    tempDir.toFile().deleteOnExit();
    try (OutputStream outputStream = response.raw().getOutputStream()) {
        Path excelFile = tempDir.resolve("download.xlsx");
        MolgenisIO.toExcelFile(excelFile, table);
        response.type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.header("Content-Disposition", "attachment; filename=" + table.getSchema().getMetadata().getName() + "_" + table.getName() + System.currentTimeMillis() + ".xlsx");
        outputStream.write(Files.readAllBytes(excelFile));
        return "Export success";
    }
}
Also used : Path(java.nio.file.Path) MolgenisWebservice.getTable(org.molgenis.emx2.web.MolgenisWebservice.getTable) Table(org.molgenis.emx2.Table) OutputStream(java.io.OutputStream) MolgenisException(org.molgenis.emx2.MolgenisException)

Example 12 with MolgenisException

use of org.molgenis.emx2.MolgenisException in project molgenis-emx2 by molgenis.

the class FileApi method getFile.

public static String getFile(Request request, Response response) throws IOException {
    String tableName = request.params("table");
    String columnName = request.params("column");
    String id = request.params("id");
    Schema schema = getSchema(request);
    Table t = schema.getTable(tableName);
    if (t == null) {
        throw new MolgenisException("Download failed: Table '" + tableName + "' not found in schema " + schema.getName());
    }
    Column c = t.getMetadata().getColumn(columnName);
    if (c == null) {
        throw new MolgenisException("Download failed: Column '" + columnName + "' not found in table " + schema.getName() + "." + tableName);
    }
    List<Row> result = t.query().select(t.getMetadata().getPrimaryKeyFields().stream().map(f -> s(f.getName())).toArray(SelectColumn[]::new)).select(s(columnName, s("contents"), s("mimetype"), s("extension"))).where(f(columnName, f("id", EQUALS, id))).retrieveRows();
    if (result.size() != 1) {
        throw new MolgenisException("Download failed: file id '" + id + "' not found in table " + tableName);
    }
    String ext = result.get(0).getString(columnName + "_extension");
    String mimetype = result.get(0).getString(columnName + "_mimetype");
    byte[] contents = result.get(0).getBinary(columnName + "_contents");
    response.raw().setHeader("Content-Disposition", "attachment; filename=" + c.getName() + "." + ext);
    response.raw().setContentType(mimetype);
    try (OutputStream out = response.raw().getOutputStream()) {
        // autoclosing
        out.write(contents);
        out.flush();
    }
    return "";
}
Also used : EQUALS(org.molgenis.emx2.Operator.EQUALS) OutputStream(java.io.OutputStream) Spark.get(spark.Spark.get) List(java.util.List) MolgenisWebservice.getSchema(org.molgenis.emx2.web.MolgenisWebservice.getSchema) Request(spark.Request) FilterBean.f(org.molgenis.emx2.FilterBean.f) Response(spark.Response) IOException(java.io.IOException) org.molgenis.emx2(org.molgenis.emx2) SelectColumn.s(org.molgenis.emx2.SelectColumn.s) MolgenisWebservice.getSchema(org.molgenis.emx2.web.MolgenisWebservice.getSchema) OutputStream(java.io.OutputStream)

Example 13 with MolgenisException

use of org.molgenis.emx2.MolgenisException in project molgenis-emx2 by molgenis.

the class GraphqlApi method getVariablesFromRequest.

private static Map<String, Object> getVariablesFromRequest(Request request) {
    if ("POST".equals(request.requestMethod())) {
        try {
            if (request.headers("Content-Type").startsWith("multipart/form-data")) {
                Map<String, Object> variables = new ObjectMapper().readValue(request.queryParams(VARIABLES), Map.class);
                // now replace each part id with the part
                putPartsIntoMap(variables, request.raw().getParts().stream().filter(p -> !p.getName().equals(VARIABLES) && !p.getName().equals(QUERY)).collect(Collectors.toList()));
                // 
                return variables;
            } else {
                Map<String, Object> node = new ObjectMapper().readValue(request.body(), Map.class);
                return (Map<String, Object>) node.get(VARIABLES);
            }
        } catch (Exception e) {
            throw new MolgenisException("Parsing of graphql variables failed. Should be an object with each graphql variable a key. " + e.getMessage(), e);
        }
    }
    return null;
}
Also used : MolgenisException(org.molgenis.emx2.MolgenisException) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) MolgenisException(org.molgenis.emx2.MolgenisException) IOException(java.io.IOException) GraphqlException(org.molgenis.emx2.graphql.GraphqlException)

Example 14 with MolgenisException

use of org.molgenis.emx2.MolgenisException in project molgenis-emx2 by molgenis.

the class TestReadWriteStores method executeTest.

public static void executeTest(TableStore store) throws IOException, MolgenisException {
    List<Row> rows = new ArrayList<>();
    int count = 10;
    for (int i = 1; i <= count; i++) {
        rows.add(new Row().setString("stringCol", "test" + i).setInt("intCol", i).setDecimal("decimalCol", Double.valueOf(i / 2)).setUuid("uuidCol", UUID.randomUUID()).setDate("dateCol", LocalDate.of(2019, 12, 12)).setDateTime("datetimeCol", LocalDateTime.now()).setBool("boolCol", true).setStringArray("stringarrayCol", new String[] { "a", "b,including comma," }).setIntArray("intarrayCol", new Integer[] { 1, 2 }).setDecimalArray("doubleArrayCol", new Double[] { 1.0, 2.0 }).setDecimalArray("doubleArrayCol", new Double[] { 1.0, 2.0 }).setDateArray("dateArray", new LocalDate[] { LocalDate.of(2019, 12, 12), LocalDate.of(2019, 12, 12) }).setDateTimeArray("datetimeArrayCol", new LocalDateTime[] { LocalDateTime.now(), LocalDateTime.now() }).setBoolArray("booleanArrayCol", new Boolean[] { true, false }));
    }
    StopWatch.start("created some rows");
    // write them
    store.writeTable("test", List.of(), rows);
    store.writeTable("test2", List.of(), rows);
    StopWatch.print("wrote them to " + store.getClass().getSimpleName(), count);
    List<Row> rows2 = StreamSupport.stream(store.readTable("test2").spliterator(), false).collect(Collectors.toList());
    // for (Row r : rows2) System.out.println(r);
    StopWatch.print("fromReader them back from " + store.getClass().getSimpleName(), count);
    // compare
    CompareTools.assertEquals(rows, rows2);
    // write another one
    store.writeTable("test3", List.of(), rows);
    StopWatch.print("wrote them to " + store.getClass().getSimpleName(), count);
    rows2 = StreamSupport.stream(store.readTable("test3").spliterator(), false).collect(Collectors.toList());
    // for (Row r : rows2) System.out.println(r);
    StopWatch.print("fromReader them back from " + store.getClass().getSimpleName(), count);
    // compare
    CompareTools.assertEquals(rows, rows2);
    StopWatch.print("compared succesfully");
    // write empty
    store.writeTable("test4", List.of("empty"), new ArrayList<>());
    // test that reading store that doesn't exist errors properly
    try {
        store.readTable("fake");
        fail("should have failed");
    } catch (MolgenisException me) {
        System.out.println("errored correctly:" + me);
    }
}
Also used : ArrayList(java.util.ArrayList) MolgenisException(org.molgenis.emx2.MolgenisException) Row(org.molgenis.emx2.Row) LocalDate(java.time.LocalDate)

Example 15 with MolgenisException

use of org.molgenis.emx2.MolgenisException in project molgenis-emx2 by molgenis.

the class TestReadWriteStores method testExcelStore.

@Test
public void testExcelStore() throws IOException {
    Path tmp = Files.createTempDirectory(null);
    try {
        Path excelFile = tmp.resolve("test.xlsx");
        System.out.println("defined excel file " + excelFile);
        TableStoreForXlsxFile store = new TableStoreForXlsxFile(excelFile);
        executeTest(store);
    } catch (MolgenisException e) {
        e.printStackTrace();
    } finally {
        Files.walk(tmp).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
    }
    if (Files.exists(tmp))
        throw new RuntimeException("TMP directory " + tmp + " not deleted. This should never happen.");
}
Also used : Path(java.nio.file.Path) MolgenisException(org.molgenis.emx2.MolgenisException) File(java.io.File) Test(org.junit.Test)

Aggregations

MolgenisException (org.molgenis.emx2.MolgenisException)41 Path (java.nio.file.Path)9 Test (org.junit.Test)9 ArrayList (java.util.ArrayList)7 Row (org.molgenis.emx2.Row)7 IOException (java.io.IOException)6 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 File (java.io.File)5 Column (org.molgenis.emx2.Column)5 ZipFile (java.util.zip.ZipFile)4 Schema (org.molgenis.emx2.Schema)4 Table (org.molgenis.emx2.Table)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 OutputStream (java.io.OutputStream)3 Writer (java.io.Writer)3 FileSystem (java.nio.file.FileSystem)3 java.util (java.util)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ZipEntry (java.util.zip.ZipEntry)3 org.molgenis.emx2 (org.molgenis.emx2)3