Search in sources :

Example 1 with ImportProvider

use of eu.esdihumboldt.hale.common.core.io.ImportProvider in project hale by halestudio.

the class SQLSchemaPage method updateState.

private boolean updateState(boolean runQuery) {
    boolean typeValid = false;
    boolean sqlValid = false;
    String error = null;
    String message = null;
    if (typeName != null) {
        // check type name
        String type = typeName.getText();
        typeValid = type != null && !type.isEmpty();
        if (typeValid) {
            // check if the name already exists in the source schema
            SchemaService schemas = HaleUI.getServiceProvider().getService(SchemaService.class);
            if (schemas != null) {
                TypeDefinition existing = schemas.getSchemas(SchemaSpaceID.SOURCE).getType(new QName(SQLSchemaReader.NAMESPACE, type));
                if (existing != null) {
                    typeValid = false;
                    error = "An SQL query with this name already exists";
                }
            }
        // also test for specific characters?
        }
    }
    if (sqlQuery != null) {
        // check SQL query
        String sql = sqlQuery.getText();
        sqlValid = sql != null && !sql.isEmpty();
        if (sqlValid) {
            String processedQuery;
            try {
                processedQuery = JDBCUtil.replaceVariables(sql, HaleUI.getServiceProvider());
            } catch (Exception e) {
                error = e.getLocalizedMessage();
                sqlValid = false;
                processedQuery = null;
            }
            // check if processed SQL query can be executed
            if (runQuery && processedQuery != null) {
                ImportProvider provider = getWizard().getProvider();
                if (provider != null && provider instanceof JDBCProvider) {
                    Connection connection = null;
                    try {
                        try {
                            connection = ((JDBCProvider) provider).getConnection();
                        } catch (SQLException e) {
                            sqlValid = false;
                            error = "Could not establish database connection: " + e.getLocalizedMessage();
                        }
                        if (connection != null) {
                            try {
                                Statement statement = JDBCUtil.createReadStatement(connection, 1);
                                try {
                                    ResultSet result = statement.executeQuery(processedQuery);
                                    int columnCount = result.getMetaData().getColumnCount();
                                    if (columnCount <= 0) {
                                        sqlValid = false;
                                        error = "Query result does not have any columns";
                                    } else {
                                        if (columnCount == 1) {
                                            message = "Successfully tested query. It yields a result with a single column.";
                                        } else {
                                            message = MessageFormat.format("Successfully tested query. It yields a result with {0} columns.", columnCount);
                                        }
                                    }
                                } catch (SQLException e) {
                                    sqlValid = false;
                                    error = "Error querying database: " + e.getMessage();
                                } finally {
                                    statement.close();
                                }
                            } catch (SQLException e) {
                                sqlValid = false;
                                error = "Could not create database statement: " + e.getMessage();
                            }
                        }
                    } finally {
                        if (connection != null) {
                            try {
                                connection.close();
                            } catch (SQLException e) {
                            // ignore
                            }
                        }
                    }
                }
            }
        }
    }
    boolean complete = typeValid && sqlValid;
    if (complete) {
        error = null;
    } else if (!typeValid && error == null) {
        error = "Please provide a name for the query";
    } else if (error == null) {
        error = "Please specify the SQL query to use";
    }
    setMessage(message);
    setErrorMessage(error);
    setPageComplete(complete);
    return complete;
}
Also used : JDBCProvider(eu.esdihumboldt.hale.io.jdbc.JDBCProvider) SQLException(java.sql.SQLException) QName(javax.xml.namespace.QName) Statement(java.sql.Statement) Connection(java.sql.Connection) ImportProvider(eu.esdihumboldt.hale.common.core.io.ImportProvider) SQLException(java.sql.SQLException) TypeDefinition(eu.esdihumboldt.hale.common.schema.model.TypeDefinition) SchemaService(eu.esdihumboldt.hale.ui.service.schema.SchemaService) ResultSet(java.sql.ResultSet)

Example 2 with ImportProvider

use of eu.esdihumboldt.hale.common.core.io.ImportProvider in project hale by halestudio.

the class IOWizard method performFinish.

/**
 * @see Wizard#performFinish()
 *
 * @return <code>true</code> if executing the I/O provider was successful
 */
@Override
public boolean performFinish() {
    if (getProvider() == null) {
        return false;
    }
    if (!applyConfiguration()) {
        return false;
    }
    // create default report
    IOReporter defReport = provider.createReporter();
    // validate and execute provider
    try {
        // validate configuration
        provider.validate();
        ProjectService ps = PlatformUI.getWorkbench().getService(ProjectService.class);
        URI projectLoc = ps.getLoadLocation() == null ? null : ps.getLoadLocation();
        boolean isProjectResource = false;
        if (actionId != null) {
            // XXX instead move project resource to action?
            ActionUI factory = ActionUIExtension.getInstance().findActionUI(actionId);
            isProjectResource = factory.isProjectResource();
        }
        // prevent loading of duplicate resources
        if (isProjectResource && provider instanceof ImportProvider && !getProviderFactory().allowDuplicateResource()) {
            String currentResource = ((ImportProvider) provider).getSource().getLocation().toString();
            URI currentAbsolute = URI.create(currentResource);
            if (projectLoc != null && !currentAbsolute.isAbsolute()) {
                currentAbsolute = projectLoc.resolve(currentAbsolute);
            }
            for (IOConfiguration conf : ((Project) ps.getProjectInfo()).getResources()) {
                Value otherResourceValue = conf.getProviderConfiguration().get(ImportProvider.PARAM_SOURCE);
                if (otherResourceValue == null) {
                    continue;
                }
                String otherResource = otherResourceValue.as(String.class);
                URI otherAbsolute = URI.create(otherResource);
                if (projectLoc != null && !otherAbsolute.isAbsolute()) {
                    otherAbsolute = projectLoc.resolve(otherAbsolute);
                }
                String action = conf.getActionId();
                // resource is already loaded into the project
                if (currentAbsolute.equals(otherAbsolute) && Objects.equal(actionId, action)) {
                    // check if the resource is loaded with a provider that
                    // allows duplicates
                    boolean allowDuplicate = false;
                    IOProviderDescriptor providerFactory = IOProviderExtension.getInstance().getFactory(conf.getProviderId());
                    if (providerFactory != null) {
                        allowDuplicate = providerFactory.allowDuplicateResource();
                    }
                    if (!allowDuplicate) {
                        log.userError("Resource is already loaded. Loading duplicate resources is aborted!");
                        return false;
                    }
                }
            }
        }
        // enable provider internal caching
        if (isProjectResource && provider instanceof CachingImportProvider) {
            ((CachingImportProvider) provider).setProvideCache();
        }
        IOReport report = execute(provider, defReport);
        if (report != null) {
            // add report to report server
            ReportService repService = PlatformUI.getWorkbench().getService(ReportService.class);
            repService.addReport(report);
            // show message to user
            if (report.isSuccess()) {
                // let advisor handle results
                try {
                    getContainer().run(true, false, new IRunnableWithProgress() {

                        @Override
                        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                            monitor.beginTask("Completing operation...", IProgressMonitor.UNKNOWN);
                            try {
                                advisor.handleResults(getProvider());
                            } finally {
                                monitor.done();
                            }
                        }
                    });
                } catch (InvocationTargetException e) {
                    log.userError("Error processing results:\n" + e.getCause().getLocalizedMessage(), e.getCause());
                    return false;
                } catch (Exception e) {
                    log.userError("Error processing results:\n" + e.getLocalizedMessage(), e);
                    return false;
                }
                // add to project service if necessary
                if (isProjectResource)
                    ps.rememberIO(actionId, getProviderFactory().getIdentifier(), provider);
                return true;
            } else {
                // error message
                log.userError(report.getSummary() + "\nPlease see the report for details.");
                return false;
            }
        } else
            return true;
    } catch (IOProviderConfigurationException e) {
        // user feedback
        log.userError("Validation of the provider configuration failed:\n" + e.getLocalizedMessage(), e);
        return false;
    }
}
Also used : IOProviderDescriptor(eu.esdihumboldt.hale.common.core.io.extension.IOProviderDescriptor) IOConfiguration(eu.esdihumboldt.hale.common.core.io.project.model.IOConfiguration) ProjectService(eu.esdihumboldt.hale.ui.service.project.ProjectService) ActionUI(eu.esdihumboldt.hale.ui.io.action.ActionUI) CachingImportProvider(eu.esdihumboldt.hale.common.core.io.CachingImportProvider) ImportProvider(eu.esdihumboldt.hale.common.core.io.ImportProvider) IOReport(eu.esdihumboldt.hale.common.core.io.report.IOReport) URI(java.net.URI) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOProviderConfigurationException(eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) Project(eu.esdihumboldt.hale.common.core.io.project.model.Project) IOReporter(eu.esdihumboldt.hale.common.core.io.report.IOReporter) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IOProviderConfigurationException(eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException) ReportService(eu.esdihumboldt.hale.ui.service.report.ReportService) CachingImportProvider(eu.esdihumboldt.hale.common.core.io.CachingImportProvider) Value(eu.esdihumboldt.hale.common.core.io.Value)

Example 3 with ImportProvider

use of eu.esdihumboldt.hale.common.core.io.ImportProvider in project hale by halestudio.

the class CharsetConfigurationPage method createContent.

@Override
protected void createContent(Composite page) {
    boolean showDetectButton = mode == Mode.manualAllowDetect || mode == Mode.autoDetect;
    GridLayoutFactory.swtDefaults().numColumns((showDetectButton) ? (3) : (2)).applyTo(page);
    Label clabel = new Label(page, SWT.NONE);
    clabel.setText("Charset: ");
    charsetCombo = new Combo(page, SWT.NONE);
    charsetCombo.setItems(Charset.availableCharsets().keySet().toArray(new String[Charset.availableCharsets().size()]));
    charsetCombo.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            update();
        }
    });
    charsetCombo.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            update();
        }
    });
    if (showDetectButton) {
        detectButton = new Button(page, SWT.NONE);
        detectButton.setText("Detect");
        detectButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                ImportProvider pro = (ImportProvider) getWizard().getProvider();
                if (pro.getSource() != null) {
                    try {
                        detectCharset(pro.getSource());
                    } catch (IOException e1) {
                        log.userError("Character encoding detection failed.", e1);
                    }
                } else {
                    log.userError("Source on import provider not set, cannot detect encoding.");
                }
            }
        });
    }
    update();
}
Also used : ModifyEvent(org.eclipse.swt.events.ModifyEvent) ModifyListener(org.eclipse.swt.events.ModifyListener) Button(org.eclipse.swt.widgets.Button) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) Label(org.eclipse.swt.widgets.Label) SelectionEvent(org.eclipse.swt.events.SelectionEvent) ImportProvider(eu.esdihumboldt.hale.common.core.io.ImportProvider) Combo(org.eclipse.swt.widgets.Combo) IOException(java.io.IOException)

Example 4 with ImportProvider

use of eu.esdihumboldt.hale.common.core.io.ImportProvider in project hale by halestudio.

the class CharsetConfigurationPage method enable.

@Override
public void enable() {
    // select I/O provider default charset
    IOProvider pro = getWizard().getProvider();
    if (pro != null) {
        Charset cs = pro.getCharset();
        if (cs != null) {
            setCharset(cs.name());
            update();
        }
        if (detectButton != null) {
            detectButton.setEnabled(pro instanceof ImportProvider);
        }
    }
}
Also used : Charset(java.nio.charset.Charset) ImportProvider(eu.esdihumboldt.hale.common.core.io.ImportProvider) IOProvider(eu.esdihumboldt.hale.common.core.io.IOProvider)

Example 5 with ImportProvider

use of eu.esdihumboldt.hale.common.core.io.ImportProvider in project hale by halestudio.

the class ActionProjectFile method apply.

/**
 * @see ProjectFile#apply()
 */
@SuppressWarnings("unchecked")
@Override
public void apply() {
    if (applyFile == null) {
        return;
    }
    try {
        // load the temporary file using an ImportProvider
        LocatableInputSupplier<? extends InputStream> tmpIn = new FileIOSupplier(applyFile);
        // get the action
        IOAction action = IOActionExtension.getInstance().get(loadActionId);
        checkState(ImportProvider.class.isAssignableFrom(action.getProviderType()), "Load action not compatible to ImportProvider");
        // try specified provider
        ImportProvider provider = null;
        if (loadProviderId != null) {
            try {
                provider = (ImportProvider) HaleIO.createIOProvider(action.getProviderType(), null, loadProviderId);
            } catch (Exception e) {
                // ignore
                log.error("Could not get specified import provider, trying auto-detection instead", e);
            }
        }
        // find provider if necessary
        if (provider == null) {
            provider = (ImportProvider) HaleIO.findIOProvider(action.getProviderType(), tmpIn, null);
        }
        if (provider == null) {
            throw new IllegalStateException("No provider for loading project file found (Action ID " + action.getId() + ")");
        }
        // find advisor
        @SuppressWarnings("rawtypes") IOAdvisor advisor = getLoadAdvisor(loadActionId, serviceProvider);
        checkState(advisor != null, "No advisor for loading project file found");
        // configure provider
        // set given parameters
        setParameters(provider, loadParameters);
        // set source
        provider.setSource(tmpIn);
        // execute the provider
        executeProvider(provider, advisor);
    } catch (Exception e) {
        // project file apply fails currently are one logged (the project
        // reader is not involved with it)
        log.error("Error applying loaded project file", e);
    } finally {
        if (!applyFile.delete()) {
            applyFile.deleteOnExit();
            applyFile = null;
        }
    }
}
Also used : IOAdvisor(eu.esdihumboldt.hale.common.core.io.IOAdvisor) ImportProvider(eu.esdihumboldt.hale.common.core.io.ImportProvider) FileIOSupplier(eu.esdihumboldt.hale.common.core.io.supplier.FileIOSupplier) IOAction(eu.esdihumboldt.hale.common.core.io.IOAction) IOException(java.io.IOException)

Aggregations

ImportProvider (eu.esdihumboldt.hale.common.core.io.ImportProvider)5 IOException (java.io.IOException)2 CachingImportProvider (eu.esdihumboldt.hale.common.core.io.CachingImportProvider)1 IOAction (eu.esdihumboldt.hale.common.core.io.IOAction)1 IOAdvisor (eu.esdihumboldt.hale.common.core.io.IOAdvisor)1 IOProvider (eu.esdihumboldt.hale.common.core.io.IOProvider)1 IOProviderConfigurationException (eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException)1 Value (eu.esdihumboldt.hale.common.core.io.Value)1 IOProviderDescriptor (eu.esdihumboldt.hale.common.core.io.extension.IOProviderDescriptor)1 IOConfiguration (eu.esdihumboldt.hale.common.core.io.project.model.IOConfiguration)1 Project (eu.esdihumboldt.hale.common.core.io.project.model.Project)1 IOReport (eu.esdihumboldt.hale.common.core.io.report.IOReport)1 IOReporter (eu.esdihumboldt.hale.common.core.io.report.IOReporter)1 FileIOSupplier (eu.esdihumboldt.hale.common.core.io.supplier.FileIOSupplier)1 TypeDefinition (eu.esdihumboldt.hale.common.schema.model.TypeDefinition)1 JDBCProvider (eu.esdihumboldt.hale.io.jdbc.JDBCProvider)1 ActionUI (eu.esdihumboldt.hale.ui.io.action.ActionUI)1 ProjectService (eu.esdihumboldt.hale.ui.service.project.ProjectService)1 ReportService (eu.esdihumboldt.hale.ui.service.report.ReportService)1 SchemaService (eu.esdihumboldt.hale.ui.service.schema.SchemaService)1