Search in sources :

Example 1 with ATransaction

use of de.fhg.igd.slf4jplus.ATransaction in project hale by halestudio.

the class XercesValidator method validate.

/**
 * @see Validator#validate(InputStream)
 */
@Override
public Report validate(InputStream xml) {
    final ReportImpl report = new ReportImpl();
    SAXParser parser = new SAXParser();
    // $NON-NLS-1$
    setFeature(parser, "http://xml.org/sax/features/validation", true);
    // $NON-NLS-1$
    setFeature(parser, "http://apache.org/xml/features/validation/schema", true);
    parser.setErrorHandler(new ReportErrorHandler(report) {

        @Override
        public void error(SAXParseException e) throws SAXException {
            // XXX this error occurs even if the element is present
            if (e.getMessage().equals("cvc-elt.1: Cannot find the declaration of element 'gml:FeatureCollection'.")) {
                // $NON-NLS-1$
                return;
            }
            super.error(e);
        }
    });
    // $NON-NLS-1$
    ATransaction trans = log.begin("Validating XML file");
    try {
        parser.parse(new InputSource(xml));
        return report;
    } catch (Exception e) {
        // $NON-NLS-1$
        throw new IllegalStateException("Error validating XML file", e);
    } finally {
        try {
            xml.close();
        } catch (IOException e) {
        // ignore
        }
        trans.end();
    }
}
Also used : InputSource(org.xml.sax.InputSource) SAXParseException(org.xml.sax.SAXParseException) ATransaction(de.fhg.igd.slf4jplus.ATransaction) SAXParser(org.apache.xerces.parsers.SAXParser) IOException(java.io.IOException) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) IOException(java.io.IOException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException)

Example 2 with ATransaction

use of de.fhg.igd.slf4jplus.ATransaction in project hale by halestudio.

the class StoreInstancesJob method run.

/**
 * @see Job#run(IProgressMonitor)
 */
@Override
public IStatus run(IProgressMonitor monitor) {
    boolean exactProgress = instances.hasSize();
    monitor.beginTask("Store instances in database", (exactProgress) ? (instances.size()) : (IProgressMonitor.UNKNOWN));
    AtomicInteger count = new AtomicInteger(0);
    TObjectIntHashMap<QName> typeCount = new TObjectIntHashMap<>();
    if (report != null) {
        // set the correct start time
        report.setStartTime(new Date());
    }
    // get database connection
    DatabaseReference<ODatabaseDocumentTx> ref = database.openWrite();
    ODatabaseDocumentTx db = ref.getDatabase();
    ATransaction trans = log.begin("Store instances in database");
    try {
        // use intent
        db.declareIntent(new OIntentMassiveInsert());
        // Find all the InstanceProcessors to feed them the stored Instances
        final List<InstanceProcessor> processors;
        if (doProcessing) {
            final InstanceProcessingExtension ext = new InstanceProcessingExtension(serviceProvider);
            processors = ext.getInstanceProcessors();
        } else {
            processors = Collections.emptyList();
        }
        BrowseOrientInstanceCollection browser = new BrowseOrientInstanceCollection(database, null, DataSet.SOURCE);
        final InstanceIndexService indexService;
        if (doProcessing) {
            indexService = serviceProvider.getService(InstanceIndexService.class);
        } else {
            indexService = null;
        }
        // TODO decouple next() and save()?
        SimpleLogContext.withLog(report, () -> {
            if (report != null && instances instanceof LogAware) {
                ((LogAware) instances).setLog(report);
            }
            ResourceIterator<Instance> it = instances.iterator();
            int size = instances.size();
            try {
                while (it.hasNext() && !monitor.isCanceled()) {
                    // last count update
                    long lastUpdate = 0;
                    if (report != null && instances instanceof LogAware) {
                        ((LogAware) instances).setLog(report);
                    }
                    Instance instance = it.next();
                    // further processing before storing
                    processInstance(instance);
                    // get/create OInstance
                    OInstance conv = ((instance instanceof OInstance) ? ((OInstance) instance) : (new OInstance(instance)));
                    conv.setInserted(true);
                    // update the instance to store, e.g. generating
                    // metadata
                    updateInstance(conv);
                    ODatabaseRecordThreadLocal.INSTANCE.set(db);
                    // configure the document
                    ODocument doc = conv.configureDocument(db);
                    // and save it
                    doc.save();
                    // Create an InstanceReference for the saved instance
                    // and
                    // feed it to all known InstanceProcessors. The
                    // decoration
                    // with ResolvableInstanceReference allows the
                    // InstanceProcessors to resolve the instances if
                    // required.
                    OrientInstanceReference oRef = new OrientInstanceReference(doc.getIdentity(), conv.getDataSet(), conv.getDefinition());
                    IdentifiableInstanceReference idRef = new IdentifiableInstanceReference(oRef, doc.getIdentity());
                    ResolvableInstanceReference resolvableRef = new ResolvableInstanceReference(idRef, browser);
                    processors.forEach(p -> p.process(instance, resolvableRef));
                    if (indexService != null) {
                        indexService.add(instance, resolvableRef);
                    }
                    count.incrementAndGet();
                    TypeDefinition type = instance.getDefinition();
                    if (type != null) {
                        typeCount.adjustOrPutValue(type.getName(), 1, 1);
                    }
                    if (exactProgress) {
                        monitor.worked(1);
                    }
                    long now = System.currentTimeMillis();
                    if (now - lastUpdate > 100) {
                        // only update every 100
                        // milliseconds
                        monitor.subTask(MessageFormat.format("{0}{1} instances processed", String.valueOf(count.get()), size != InstanceCollection.UNKNOWN_SIZE ? "/" + String.valueOf(size) : ""));
                        lastUpdate = now;
                    }
                }
            } finally {
                it.close();
                if (report != null && instances instanceof LogAware) {
                    ((LogAware) instances).setLog(null);
                }
            }
        });
        db.declareIntent(null);
    } catch (RuntimeException e) {
        if (report != null) {
            reportTypeCount(report, typeCount);
            report.error(new MessageImpl("Error storing instances in database", e));
            report.setSuccess(false);
            reportHandler.publishReport(report);
        }
        throw e;
    } finally {
        ref.dispose();
        trans.end();
        /*
			 * Reset instances to prevent memory leak. It seems Eclipse
			 * internally holds a reference to the job (in JobInfo and/or
			 * ProgressMonitorFocusJobDialog) and this results in the instance
			 * collection not being garbage collected. This is especially bad,
			 * if an in-memory instance collection is used, e.g. a
			 * DefaultInstanceCollection that is used when loading a Shapefile.
			 */
        instances = null;
    }
    try {
        onComplete();
    } catch (RuntimeException e) {
        String message = "Error while post processing stored instances";
        if (report != null) {
            report.error(new MessageImpl(message, e));
        } else {
            log.error(message, e);
        }
    }
    String message = MessageFormat.format("Stored {0} instances in the database.", count);
    if (monitor.isCanceled()) {
        String warn = "Loading instances was canceled, incomplete data set in the database.";
        if (report != null) {
            report.warn(new MessageImpl(warn, null));
        } else {
            log.warn(warn);
        }
    }
    if (report != null) {
        reportTypeCount(report, typeCount);
        report.setSuccess(true);
        report.setSummary(message);
        reportHandler.publishReport(report);
    } else {
        log.info(message);
    }
    monitor.done();
    return new Status((monitor.isCanceled()) ? (IStatus.CANCEL) : (IStatus.OK), "eu.esdihumboldt.hale.common.instance.orient", message);
}
Also used : MutableInstance(eu.esdihumboldt.hale.common.instance.model.MutableInstance) Instance(eu.esdihumboldt.hale.common.instance.model.Instance) OInstance(eu.esdihumboldt.hale.common.instance.orient.OInstance) IdentifiableInstanceReference(eu.esdihumboldt.hale.common.instance.model.IdentifiableInstanceReference) ODatabaseDocumentTx(com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx) OInstance(eu.esdihumboldt.hale.common.instance.orient.OInstance) OIntentMassiveInsert(com.orientechnologies.orient.core.intent.OIntentMassiveInsert) TypeDefinition(eu.esdihumboldt.hale.common.schema.model.TypeDefinition) TObjectIntHashMap(gnu.trove.TObjectIntHashMap) InstanceProcessor(eu.esdihumboldt.hale.common.instance.processing.InstanceProcessor) InstanceIndexService(eu.esdihumboldt.hale.common.instance.index.InstanceIndexService) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) LogAware(eu.esdihumboldt.hale.common.core.report.LogAware) QName(javax.xml.namespace.QName) Date(java.util.Date) InstanceProcessingExtension(eu.esdihumboldt.hale.common.instance.processing.InstanceProcessingExtension) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ATransaction(de.fhg.igd.slf4jplus.ATransaction) ResolvableInstanceReference(eu.esdihumboldt.hale.common.instance.model.ResolvableInstanceReference) MessageImpl(eu.esdihumboldt.hale.common.core.report.impl.MessageImpl)

Example 3 with ATransaction

use of de.fhg.igd.slf4jplus.ATransaction in project hale by halestudio.

the class ExportJob method run.

/**
 * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
 */
@Override
protected IStatus run(IProgressMonitor monitor) {
    IOReporter defaultReporter = writer.createReporter();
    defaultReporter.setSuccess(false);
    IOReport report = defaultReporter;
    try {
        ATransaction trans = log.begin(defaultReporter.getTaskName());
        try {
            IOReport result = writer.execute(new ProgressMonitorIndicator(monitor));
            if (result != null) {
                report = result;
            } else {
                defaultReporter.setSuccess(true);
            }
        } catch (Throwable e) {
            defaultReporter.error(new IOMessageImpl(e.getLocalizedMessage(), e));
        } finally {
            trans.end();
        }
    } catch (Throwable e) {
        defaultReporter.error(new IOMessageImpl(e.getLocalizedMessage(), e));
    }
    if (monitor.isCanceled()) {
        reset();
        return Status.CANCEL_STATUS;
    }
    // add report to report service
    reportHandler.publishReport(report);
    // show message to user
    if (report.isSuccess()) {
        // no message, we rely on the report being
        // shown/processed
        // let advisor handle results
        advisor.handleResults(writer);
        reset();
        return Status.OK_STATUS;
    } else {
        reset();
        log.error(report.getSummary());
        return new Status(Status.ERROR, "eu.esdihumboldt.hale.common.headless", report.getSummary(), null);
    }
}
Also used : Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) IOReporter(eu.esdihumboldt.hale.common.core.io.report.IOReporter) ProgressMonitorIndicator(eu.esdihumboldt.hale.common.core.io.ProgressMonitorIndicator) ATransaction(de.fhg.igd.slf4jplus.ATransaction) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl) IOReport(eu.esdihumboldt.hale.common.core.io.report.IOReport)

Example 4 with ATransaction

use of de.fhg.igd.slf4jplus.ATransaction in project hale by halestudio.

the class ValidationJob method run.

/**
 * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
 */
@Override
protected IStatus run(IProgressMonitor monitor) {
    boolean successful = true;
    for (InstanceValidator validator : this.validators) {
        IOReporter defaultReporter = validator.createReporter();
        defaultReporter.setSuccess(false);
        IOReport report = defaultReporter;
        try {
            ATransaction trans = log.begin(defaultReporter.getTaskName());
            try {
                if (writer != null) {
                    // set validation schemas (may have been determined only
                    // during writer execution)
                    // set schemas
                    List<? extends Locatable> schemas = writer.getValidationSchemas();
                    validator.setSchemas(schemas.toArray(new Locatable[schemas.size()]));
                }
                validator.setServiceProvider(serviceProvider);
                IOReport result = validator.execute(new ProgressMonitorIndicator(monitor));
                if (result != null) {
                    report = result;
                } else {
                    defaultReporter.setSuccess(true);
                }
            } catch (Throwable e) {
                defaultReporter.error(new IOMessageImpl(e.getLocalizedMessage(), e));
            } finally {
                trans.end();
            }
        } catch (Throwable e) {
            defaultReporter.error(new IOMessageImpl(e.getLocalizedMessage(), e));
        }
        if (monitor.isCanceled()) {
            reset();
            return Status.CANCEL_STATUS;
        }
        // add report to report service
        reportHandler.publishReport(report);
        // show message to user
        if (report.isSuccess()) {
            // info message
            log.info(report.getSummary());
        } else {
            // error message
            log.error(report.getSummary());
            successful = false;
        }
    }
    reset();
    if (successful) {
        log.userInfo("All validations completed successfully.");
        return Status.OK_STATUS;
    } else {
        log.userError("There were validation failures. Please check the reports for details.");
        return ERROR_STATUS;
    }
}
Also used : InstanceValidator(eu.esdihumboldt.hale.common.instance.io.InstanceValidator) IOReporter(eu.esdihumboldt.hale.common.core.io.report.IOReporter) ProgressMonitorIndicator(eu.esdihumboldt.hale.common.core.io.ProgressMonitorIndicator) ATransaction(de.fhg.igd.slf4jplus.ATransaction) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl) IOReport(eu.esdihumboldt.hale.common.core.io.report.IOReport) Locatable(eu.esdihumboldt.hale.common.core.io.supplier.Locatable)

Example 5 with ATransaction

use of de.fhg.igd.slf4jplus.ATransaction in project hale by halestudio.

the class HeadlessIO method executeProvider.

/**
 * Execute the given I/O provider with the given I/O advisor.
 *
 * @param provider the I/O provider
 * @param advisor the I/O advisor
 * @param progress the progress indicator, may be <code>null</code>
 * @param reportHandler the report handler, may be <code>null</code>
 * @throws IOException if executing the provider fails
 */
@SuppressWarnings("unchecked")
public static void executeProvider(final IOProvider provider, @SuppressWarnings("rawtypes") final IOAdvisor advisor, ProgressIndicator progress, ReportHandler reportHandler) throws IOException {
    IOReporter reporter = provider.createReporter();
    ATransaction trans = log.begin(reporter.getTaskName());
    try {
        // use advisor to configure provider
        advisor.prepareProvider(provider);
        advisor.updateConfiguration(provider);
        // execute
        IOReport report = provider.execute(progress);
        if (reportHandler != null) {
            reportHandler.publishReport(report);
        }
        // handle results
        if (report.isSuccess()) {
            advisor.handleResults(provider);
        } else {
            throw new IOException("Executing I/O provider not successful: " + report.getSummary());
        }
    } catch (Exception e) {
        throw new IOException("Error executing an I/O provider.", e);
    } finally {
        trans.end();
    }
}
Also used : IOReporter(eu.esdihumboldt.hale.common.core.io.report.IOReporter) ATransaction(de.fhg.igd.slf4jplus.ATransaction) IOReport(eu.esdihumboldt.hale.common.core.io.report.IOReport) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

ATransaction (de.fhg.igd.slf4jplus.ATransaction)14 IOReport (eu.esdihumboldt.hale.common.core.io.report.IOReport)6 ProgressMonitorIndicator (eu.esdihumboldt.hale.common.core.io.ProgressMonitorIndicator)5 IOReporter (eu.esdihumboldt.hale.common.core.io.report.IOReporter)5 IOException (java.io.IOException)4 IOMessageImpl (eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl)3 ExampleProject (eu.esdihumboldt.hale.doc.user.examples.internal.extension.ExampleProject)3 ReportService (eu.esdihumboldt.hale.ui.service.report.ReportService)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)3 IRunnableWithProgress (org.eclipse.jface.operation.IRunnableWithProgress)3 Alignment (eu.esdihumboldt.hale.common.align.model.Alignment)2 CachingImportProvider (eu.esdihumboldt.hale.common.core.io.CachingImportProvider)2 Instance (eu.esdihumboldt.hale.common.instance.model.Instance)2 MutableInstance (eu.esdihumboldt.hale.common.instance.model.MutableInstance)2 QName (javax.xml.namespace.QName)2 IStatus (org.eclipse.core.runtime.IStatus)2 Status (org.eclipse.core.runtime.Status)2 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)1 OIntentMassiveInsert (com.orientechnologies.orient.core.intent.OIntentMassiveInsert)1