Search in sources :

Example 16 with MolgenisException

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

the class EvaluateExpressionsTest method testCheckValidationTurnToBoolIsFalse.

@Test
public void testCheckValidationTurnToBoolIsFalse() {
    Map<String, Object> values = new HashMap<>();
    Collection<Column> columns = new ArrayList<>();
    String validation = "false";
    Column column = new Column("name");
    column.setValidation(validation);
    columns.add(column);
    try {
        checkValidation(values, columns);
    } catch (MolgenisException exception) {
        assertEquals("false. Values provided: {}", exception.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) Column(org.molgenis.emx2.Column) ArrayList(java.util.ArrayList) MolgenisException(org.molgenis.emx2.MolgenisException) Test(org.junit.Test)

Example 17 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 18 with MolgenisException

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

the class ZipApi method postZip.

static String postZip(Request request, Response response) throws MolgenisException, IOException, ServletException {
    Long start = System.currentTimeMillis();
    Schema schema = getSchema(request);
    // get uploaded file
    File tempFile = File.createTempFile("temp_", ".tmp");
    try {
        request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement(tempFile.getAbsolutePath()));
        try (InputStream input = request.raw().getPart("file").getInputStream()) {
            Files.copy(input, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
        // depending on file extension use proper importer
        String fileName = request.raw().getPart("file").getSubmittedFileName();
        if (fileName.endsWith(".zip")) {
            if (request.queryParams("async") != null) {
                String id = TaskApi.submit(new ImportCsvZipTask(tempFile.toPath(), schema, false));
                return new TaskReference(id, schema).toString();
            } else {
                MolgenisIO.fromZipFile(tempFile.toPath(), schema, false);
            }
        } else if (fileName.endsWith(".xlsx")) {
            MolgenisIO.importFromExcelFile(tempFile.toPath(), schema, false);
        } else {
            throw new IOException("File upload failed: extension " + fileName.substring(fileName.lastIndexOf('.')) + " not supported");
        }
        response.status(200);
        return "Import success in " + (System.currentTimeMillis() - start) + "ms";
    } finally {
        if (request.queryParams("async") == null) {
            Files.delete(tempFile.toPath());
        }
    }
}
Also used : MultipartConfigElement(javax.servlet.MultipartConfigElement) InputStream(java.io.InputStream) MolgenisWebservice.getSchema(org.molgenis.emx2.web.MolgenisWebservice.getSchema) Schema(org.molgenis.emx2.Schema) IOException(java.io.IOException) ImportCsvZipTask(org.molgenis.emx2.io.ImportCsvZipTask) File(java.io.File)

Example 19 with MolgenisException

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

the class ZipApi method getZipTable.

static String getZipTable(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 zipFile = tempDir.resolve("download.zip");
        MolgenisIO.toZipFile(zipFile, table);
        outputStream.write(Files.readAllBytes(zipFile));
        response.type("application/zip");
        response.header("Content-Disposition", "attachment; filename=" + table.getSchema().getMetadata().getName() + "_" + table.getName() + System.currentTimeMillis() + ".zip");
        return "Export success";
    } finally {
        try (Stream<Path> files = Files.walk(tempDir)) {
            files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
        }
    }
}
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) File(java.io.File)

Example 20 with MolgenisException

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

the class SqlTableMetadata method alterColumnTransaction.

// static to ensure we don't touch 'this' until transaction succesfull
private static SqlTableMetadata alterColumnTransaction(String schemaName, String tableName, String columnName, Column column, Database db) {
    SqlTableMetadata tm = (SqlTableMetadata) db.getSchema(schemaName).getMetadata().getTableMetadata(tableName);
    Column newColumn = new Column(tm, column);
    Column oldColumn = tm.getColumn(columnName);
    // primary keys by definition are required
    if (newColumn.getKey() == 1) {
        newColumn.setRequired(true);
    }
    validateColumn(newColumn);
    // check if reference and of different size
    if (newColumn.isRefArray() && !newColumn.getName().equals(oldColumn.getName()) && !newColumn.getColumnType().equals(oldColumn.getColumnType()) && newColumn.getRefTable().getPrimaryKeyFields().size() > 1) {
        throw new MolgenisException("Alter column of '" + oldColumn.getName() + " failed: REF_ARRAY is not supported for composite keys of table " + newColumn.getRefTableName());
    }
    // if changing 'ref' then check if not refBack exists
    if (!oldColumn.getColumnType().equals(newColumn.getColumnType())) {
        tm.checkNotRefback(columnName, oldColumn);
    }
    // drop old key, if touched
    if (oldColumn.getKey() > 0 && newColumn.getKey() != oldColumn.getKey()) {
        executeDropKey(tm.getJooq(), oldColumn.getTable(), oldColumn.getKey());
    }
    // drop referential constraints around this column
    executeRemoveRefConstraints(tm.getJooq(), oldColumn);
    // remove refBacks if exist
    executeRemoveRefback(oldColumn, newColumn);
    // add ontology table if needed
    if (newColumn.isOntology()) {
        createOntologyTable(newColumn);
    }
    // rename and retype if needed
    executeAlterType(tm.getJooq(), oldColumn, newColumn);
    executeAlterName(tm.getJooq(), oldColumn, newColumn);
    // only applies to key=1
    if ((oldColumn.isPrimaryKey() || newColumn.isPrimaryKey()) && oldColumn.isRequired() && !oldColumn.isRequired() == newColumn.isRequired()) {
        executeSetRequired(tm.getJooq(), newColumn);
    }
    // update the metadata so we can use it for new keys and references
    if (column.getPosition() == null) {
        column.setPosition(tm.columns.get(columnName).getPosition());
    }
    // remove the old
    tm.columns.remove(columnName);
    // add the new
    tm.columns.put(column.getName(), column);
    // reapply ref constrainst
    executeCreateRefConstraints(tm.getJooq(), newColumn);
    // check if refBack constraints need updating
    reapplyRefbackContraints(oldColumn, newColumn);
    // create/update key, if touched
    if (newColumn.getKey() != oldColumn.getKey()) {
        createOrReplaceKey(tm.getJooq(), tm, newColumn.getKey(), tm.getKeyFields(newColumn.getKey()));
    }
    // delete old column if name changed, then save any other metadata changes
    if (!oldColumn.getName().equals(newColumn.getName()))
        deleteColumn(tm.getJooq(), oldColumn);
    saveColumnMetadata(tm.getJooq(), newColumn);
    return tm;
}
Also used : MetadataUtils.deleteColumn(org.molgenis.emx2.sql.MetadataUtils.deleteColumn)

Aggregations

MolgenisException (org.molgenis.emx2.MolgenisException)39 Path (java.nio.file.Path)9 Test (org.junit.Test)9 ArrayList (java.util.ArrayList)7 IOException (java.io.IOException)6 Row (org.molgenis.emx2.Row)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 MetadataUtils.deleteColumn (org.molgenis.emx2.sql.MetadataUtils.deleteColumn)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 OutputStream (java.io.OutputStream)3 Writer (java.io.Writer)3 FileSystem (java.nio.file.FileSystem)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ZipEntry (java.util.zip.ZipEntry)3 org.molgenis.emx2 (org.molgenis.emx2)3