Search in sources :

Example 21 with DataAccessException

use of org.jooq.exception.DataAccessException in project jOOQ by jOOQ.

the class JPADatabase method create0.

@SuppressWarnings("serial")
@Override
protected DSLContext create0() {
    if (connection == null) {
        String packages = getProperties().getProperty("packages");
        if (isBlank(packages)) {
            packages = "";
            log.warn("No packages defined", "It is highly recommended that you provide explicit packages to scan");
        }
        try {
            connection = DriverManager.getConnection("jdbc:h2:mem:jooq-meta-extensions", "sa", "");
            MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder().applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect").applySetting("javax.persistence.schema-generation-connection", connection).applySetting(AvailableSettings.CONNECTION_PROVIDER, new ConnectionProvider() {

                @SuppressWarnings("rawtypes")
                @Override
                public boolean isUnwrappableAs(Class unwrapType) {
                    return false;
                }

                @Override
                public <T> T unwrap(Class<T> unwrapType) {
                    return null;
                }

                @Override
                public Connection getConnection() {
                    return connection;
                }

                @Override
                public void closeConnection(Connection conn) throws SQLException {
                }

                @Override
                public boolean supportsAggressiveRelease() {
                    return true;
                }
            }).build());
            ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
            scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
            // [#5845] Use the correct ClassLoader to load the jpa entity classes defined in the user project
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            for (String pkg : packages.split(",")) for (BeanDefinition def : scanner.findCandidateComponents(defaultIfBlank(pkg, "").trim())) metadata.addAnnotatedClass(Class.forName(def.getBeanClassName(), true, cl));
            // This seems to be the way to do this in idiomatic Hibernate 5.0 API
            // See also: http://stackoverflow.com/q/32178041/521799
            // SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), connection);
            // export.create(true, true);
            // Hibernate 5.2 broke 5.0 API again. Here's how to do this now:
            SchemaExport export = new SchemaExport();
            export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
        } catch (Exception e) {
            throw new DataAccessException("Error while exporting schema", e);
        }
    }
    return DSL.using(connection);
}
Also used : AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) Entity(javax.persistence.Entity) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) SQLException(java.sql.SQLException) MetadataSources(org.hibernate.boot.MetadataSources) Connection(java.sql.Connection) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) SQLException(java.sql.SQLException) DataAccessException(org.jooq.exception.DataAccessException) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) DataAccessException(org.jooq.exception.DataAccessException) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport)

Example 22 with DataAccessException

use of org.jooq.exception.DataAccessException in project jOOQ by jOOQ.

the class BarChartSample method start.

@Override
public void start(Stage stage) {
    stage.setTitle("Country statistics with jOOQ and JavaFX");
    Label error = new Label("");
    error.setPadding(new Insets(10.0));
    // Create two charts, plotting a specific metric, each.
    BarChart<String, Number> chart1 = chart(COUNTRIES.GDP_PER_CAPITA, "GDP per Capita", "USD");
    BarChart<String, Number> chart2 = chart(COUNTRIES.GOVT_DEBT, "Government Debt", "% of GDP");
    TableView<CountriesRecord> table = table(COUNTRIES);
    Runnable refresh = () -> {
        table.getItems().clear();
        table.getItems().addAll(ctx().fetch(COUNTRIES).sortAsc(COUNTRIES.YEAR).sortAsc(COUNTRIES.CODE));
        chartRefresh(chart1);
        chartRefresh(chart2);
        error.setText("");
        selected = ctx().newRecord(COUNTRIES);
    };
    refresh.run();
    table.getSelectionModel().getSelectedItems().addListener((Change<? extends CountriesRecord> c) -> {
        if (c.getList().isEmpty())
            selected = ctx().newRecord(COUNTRIES);
        else
            for (CountriesRecord record : c.getList()) selected = record;
    });
    GridPane editPane = new GridPane();
    int i = 0;
    for (Field<?> field : COUNTRIES.fields()) {
        Label label = new Label(field.getName());
        TextField textField = new TextField();
        textField.textProperty().addListener((o, oldV, newV) -> {
            selected.set((Field) field, newV);
        });
        table.getSelectionModel().getSelectedItems().addListener((Change<? extends CountriesRecord> c) -> {
            if (c.getList().isEmpty())
                textField.setText("");
            else
                for (CountriesRecord record : c.getList()) textField.setText(record.get(field, String.class));
        });
        editPane.addRow(i++, label, textField);
    }
    Button saveButton = new Button("Save");
    saveButton.setOnAction(event -> {
        try {
            if (selected.store() > 0)
                refresh.run();
        } catch (DataAccessException e) {
            e.printStackTrace();
            error.setText(e.sqlStateClass() + ": " + e.getCause().getMessage());
        }
    });
    Button deleteButton = new Button("Delete");
    deleteButton.setOnAction(event -> {
        try {
            if (selected.delete() > 0)
                refresh.run();
        } catch (DataAccessException e) {
            e.printStackTrace();
            error.setText(e.sqlStateClass() + ": " + e.getCause().getMessage());
        }
    });
    GridPane buttonPane = new GridPane();
    buttonPane.addRow(0, saveButton, deleteButton);
    editPane.addRow(i++, new Label(""), buttonPane);
    GridPane chartPane = new GridPane();
    chartPane.addColumn(0, chart1, chart2);
    grow(chartPane);
    GridPane display = new GridPane();
    display.addRow(0, chartPane, table, editPane);
    grow(display);
    GridPane displayAndStatus = new GridPane();
    displayAndStatus.addColumn(0, display, error);
    displayAndStatus.setGridLinesVisible(true);
    grow(displayAndStatus);
    Scene scene = new Scene(displayAndStatus, 1000, 800);
    stage.setScene(scene);
    stage.show();
}
Also used : Insets(javafx.geometry.Insets) GridPane(javafx.scene.layout.GridPane) CountriesRecord(org.jooq.generated.tables.records.CountriesRecord) Label(javafx.scene.control.Label) Change(javafx.collections.ListChangeListener.Change) Scene(javafx.scene.Scene) Button(javafx.scene.control.Button) TextField(javafx.scene.control.TextField) DataAccessException(org.jooq.exception.DataAccessException)

Example 23 with DataAccessException

use of org.jooq.exception.DataAccessException in project jOOQ by jOOQ.

the class DefaultDSLContext method fetchFromJSON.

@Override
public Result<Record> fetchFromJSON(String string) {
    List<String[]> list = new LinkedList<String[]>();
    JSONReader reader = null;
    try {
        reader = new JSONReader(new StringReader(string));
        List<String[]> records = reader.readAll();
        String[] fields = reader.getFields();
        list.add(fields);
        list.addAll(records);
    } catch (IOException e) {
        throw new DataAccessException("Could not read the JSON string", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ignore) {
        }
    }
    return fetchFromStringData(list);
}
Also used : StringReader(java.io.StringReader) IOException(java.io.IOException) LinkedList(java.util.LinkedList) DataAccessException(org.jooq.exception.DataAccessException)

Example 24 with DataAccessException

use of org.jooq.exception.DataAccessException in project jOOQ by jOOQ.

the class DefaultTransactionProvider method commit.

@Override
public final void commit(TransactionContext ctx) {
    Deque<Savepoint> savepoints = savepoints(ctx.configuration());
    Savepoint savepoint = savepoints.pop();
    // [#3489] Explicitly release savepoints prior to commit
    if (savepoint != null && savepoint != UNSUPPORTED_SAVEPOINT && savepoint != IGNORED_SAVEPOINT)
        try {
            connection(ctx.configuration()).releaseSavepoint(savepoint);
        }// See also http://stackoverflow.com/q/10667292/521799
         catch (DataAccessException ignore) {
        }
    // This is the top-level transaction
    if (savepoints.isEmpty()) {
        connection(ctx.configuration()).commit();
        brace(ctx.configuration(), false);
    } else // Nested commits have no effect
    {
    }
}
Also used : Savepoint(java.sql.Savepoint) DataAccessException(org.jooq.exception.DataAccessException)

Example 25 with DataAccessException

use of org.jooq.exception.DataAccessException in project jOOQ by jOOQ.

the class DefaultTransactionProvider method begin.

@Override
public final void begin(TransactionContext ctx) {
    Deque<Savepoint> savepoints = savepoints(ctx.configuration());
    // This is the top-level transaction
    if (savepoints.isEmpty())
        brace(ctx.configuration(), true);
    Savepoint savepoint = setSavepoint(ctx.configuration());
    if (savepoint == UNSUPPORTED_SAVEPOINT && !savepoints.isEmpty())
        throw new DataAccessException("Cannot nest transactions because Savepoints are not supported");
    savepoints.push(savepoint);
}
Also used : Savepoint(java.sql.Savepoint) DataAccessException(org.jooq.exception.DataAccessException)

Aggregations

DataAccessException (org.jooq.exception.DataAccessException)34 SQLException (java.sql.SQLException)14 Test (org.junit.Test)5 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)4 Timed (com.codahale.metrics.annotation.Timed)4 Connection (java.sql.Connection)4 Consumes (javax.ws.rs.Consumes)4 POST (javax.ws.rs.POST)4 Event (keywhiz.log.Event)4 SecretController (keywhiz.service.daos.SecretController)4 ConflictException (keywhiz.service.exceptions.ConflictException)4 IOException (java.io.IOException)3 SQLSyntaxErrorException (java.sql.SQLSyntaxErrorException)3 HashMap (java.util.HashMap)3 Response (javax.ws.rs.core.Response)3 SanitizedSecret (keywhiz.api.model.SanitizedSecret)3 Secret (keywhiz.api.model.Secret)3 StringReader (java.io.StringReader)2 URI (java.net.URI)2 Savepoint (java.sql.Savepoint)2