Search in sources :

Example 1 with NoStreamOutputSupplier

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

the class HaleConnectProjectWriter method execute.

@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException {
    if (!haleConnect.isLoggedIn()) {
        reporter.error("Must be logged in to hale connect to upload project.");
        reporter.setSuccess(false);
        return reporter;
    }
    URI location = null;
    if (getTarget().getLocation() != null) {
        location = getTarget().getLocation();
    }
    progress.begin("Saving project to hale connect", ProgressIndicator.UNKNOWN);
    Project project = getProject();
    URI projectUrn;
    if (location == null) {
        // was not shared before or creation of new project requested by
        // user
        boolean enableVersioning = getParameter(ENABLE_VERSIONING).as(Boolean.class);
        boolean publicAccess = getParameter(SHARING_PUBLIC).as(Boolean.class);
        String ownerTypeParameter = getParameter(OWNER_TYPE).as(String.class);
        OwnerType ownerType;
        try {
            ownerType = OwnerType.fromJsonValue(ownerTypeParameter);
        } catch (IllegalArgumentException e) {
            throw new IOProviderConfigurationException(MessageFormat.format("Invalid owner type: {0}", ownerTypeParameter), e);
        }
        String ownerId;
        switch(ownerType) {
            case USER:
                ownerId = haleConnect.getSession().getUserId();
                break;
            case ORGANISATION:
                if (haleConnect.getSession().getOrganisationIds().isEmpty()) {
                    throw new IOProviderConfigurationException(MessageFormat.format("Owner type is set to ORGANISATION but user \"{0}\" is not associated with any organisation", haleConnect.getSession().getUsername()));
                }
                ownerId = haleConnect.getSession().getOrganisationIds().iterator().next();
                break;
            default:
                throw new IOProviderConfigurationException(MessageFormat.format("Unknown owner type: {0}", ownerType));
        }
        Owner owner = new Owner(ownerType, ownerId);
        String projectId;
        try {
            projectId = haleConnect.createProject(project.getName(), project.getAuthor(), owner, enableVersioning);
            haleConnect.setProjectSharingOptions(projectId, owner, new SharingOptions(publicAccess));
        } catch (HaleConnectException e) {
            reporter.error("Error creating hale connect project", e);
            reporter.setSuccess(false);
            return reporter;
        }
        projectUrn = HaleConnectUrnBuilder.buildProjectUrn(owner, projectId);
        if (reporter instanceof MutableTargetIOReport) {
            ((MutableTargetIOReport) reporter).setTarget(new LocatableURI(prettifyTarget(projectUrn)));
        }
    } else if (!HaleConnectUrnBuilder.isValidProjectUrn(location)) {
        throw new IOProviderConfigurationException(MessageFormat.format("Cannot write to location: {0}", location.toString()));
    } else {
        projectUrn = location;
        writerMode = ProjectWriterMode.SAVE;
    }
    this.setTarget(new NoStreamOutputSupplier(projectUrn));
    // save the hale connect project URN in the project properties
    getProject().getProperties().put(HaleConnectProjectReader.HALECONNECT_URN_PROPERTY, Value.of(projectUrn.toString()));
    // redirect project archive to temporary local file
    File projectArchive = Files.createTempFile("hc-arc", ".zip").toFile();
    IOReport report;
    try (final FileOutputStream archiveStream = new FileOutputStream(projectArchive)) {
        report = createProjectArchive(archiveStream, reporter, progress);
    }
    if (!report.isSuccess()) {
        // exit when creating project archive failed
        return report;
    }
    String projectId = HaleConnectUrnBuilder.extractProjectId(projectUrn);
    Owner owner = HaleConnectUrnBuilder.extractProjectOwner(projectUrn);
    boolean result;
    try {
        result = haleConnect.uploadProjectFile(projectId, owner, projectArchive, progress);
    } catch (HaleConnectException e) {
        switch(e.getStatusCode()) {
            case 403:
                /* Forbidden */
                reporter.error(MessageFormat.format("You are not authorized to access project {0}", projectId), e);
                break;
            default:
                reporter.error(MessageFormat.format("Error uploading hale connect project: {0}", e.getMessage()), e);
        }
        reporter.setSuccess(false);
        return reporter;
    }
    // name
    try {
        haleConnect.setProjectName(projectId, owner, project.getName());
    } catch (HaleConnectException e) {
        // This is non-fatal
        log.warn(MessageFormat.format("Unable to update project bucket name for project {0}: {1}", HaleConnectUrnBuilder.buildProjectUrn(owner, projectId).toString(), e.getMessage()), e);
    }
    try {
        HaleConnectProjectInfo hcProjectInfo = haleConnect.getProject(owner, projectId);
        if (hcProjectInfo != null) {
            getProject().getProperties().put(HaleConnectProjectReader.HALECONNECT_LAST_MODIFIED_PROPERTY, Value.of(hcProjectInfo.getLastModified()));
        }
    } catch (HaleConnectException e) {
        // This is non-fatal
        log.warn(MessageFormat.format("Unable to get lastUpdated property for project {0}: {1}", HaleConnectUrnBuilder.buildProjectUrn(owner, projectId).toString(), e.getMessage()), e);
    }
    this.clientAccessUrl = HaleConnectUrnBuilder.buildClientAccessUrl(haleConnect.getBasePathManager().getBasePath(HaleConnectServices.WEB_CLIENT), owner, projectId);
    this.projectUri = HaleConnectUrnBuilder.buildProjectUrn(owner, projectId);
    reporter.setSuccess(result);
    return reporter;
}
Also used : Owner(eu.esdihumboldt.hale.io.haleconnect.Owner) LocatableURI(eu.esdihumboldt.hale.common.core.io.supplier.LocatableURI) IOReport(eu.esdihumboldt.hale.common.core.io.report.IOReport) MutableTargetIOReport(eu.esdihumboldt.hale.common.core.io.report.MutableTargetIOReport) HaleConnectException(eu.esdihumboldt.hale.io.haleconnect.HaleConnectException) HaleConnectProjectInfo(eu.esdihumboldt.hale.io.haleconnect.HaleConnectProjectInfo) URI(java.net.URI) LocatableURI(eu.esdihumboldt.hale.common.core.io.supplier.LocatableURI) Project(eu.esdihumboldt.hale.common.core.io.project.model.Project) OwnerType(eu.esdihumboldt.hale.io.haleconnect.OwnerType) IOProviderConfigurationException(eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException) FileOutputStream(java.io.FileOutputStream) NoStreamOutputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.NoStreamOutputSupplier) File(java.io.File) MutableTargetIOReport(eu.esdihumboldt.hale.common.core.io.report.MutableTargetIOReport)

Example 2 with NoStreamOutputSupplier

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

the class ProjectServiceImpl method save.

/**
 * @see ProjectService#save()
 */
@Override
public void save() {
    File projectFile;
    IOConfiguration saveConfig;
    synchronized (this) {
        projectFile = this.projectFile;
        saveConfig = main.getSaveConfiguration();
    }
    if (projectFile != null || canSaveTo(projectLocation)) {
        Collection<IOProviderDescriptor> providers = HaleIO.getProviderFactories(ProjectWriter.class);
        // use configuration from previous save if possible
        if (saveConfig != null) {
            // get provider ...
            ProjectWriter writer = null;
            for (IOProviderDescriptor factory : providers) {
                if (factory.getIdentifier().equals(saveConfig.getProviderId())) {
                    /*
						 * Check if the content type the project was loaded with
						 * is supported for saving.
						 * 
						 * Example for a changed content type: A saved project
						 * archive may have been extracted and the internal XML
						 * project file loaded.
						 */
                    if (projectLoadContentType != null) {
                        if (factory.getSupportedTypes() == null || !factory.getSupportedTypes().contains(projectLoadContentType)) {
                            log.warn("Project cannot be saved with the same settings it was originally saved with, as the content type has changed.");
                            break;
                        }
                    }
                    try {
                        writer = (ProjectWriter) factory.createExtensionObject();
                    } catch (Exception e) {
                        log.error("Could not create project writer", e);
                    }
                }
            }
            if (writer != null) {
                // configure provider
                writer.loadConfiguration(saveConfig.getProviderConfiguration());
                // moved externally)
                if (projectFile != null) {
                    writer.setTarget(new FileIOSupplier(projectFile));
                } else {
                    writer.setTarget(new NoStreamOutputSupplier(projectLocation));
                }
                ListenableFuture<IOReport> result = ProjectResourcesUtil.executeProvider(writer, saveProjectAdvisor, true, null);
                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            IOReport report = result.get();
                            if (!report.isSuccess()) {
                                log.userError("The project could not be saved. Please check the report for more details.");
                            }
                        } catch (InterruptedException | ExecutionException e) {
                            log.userError("The project could not be saved.", e);
                        }
                    }
                });
            } else {
                log.info("The project cannot be saved because the format the project was saved with is not available or has changed.");
                // use save as instead
                saveAs();
            }
        } else if (projectFile != null) {
            // use I/O provider and content type mechanisms to try saving
            // the project file
            ProjectWriter writer = HaleIO.findIOProvider(ProjectWriter.class, new FileIOSupplier(projectFile), projectFile.getAbsolutePath());
            if (writer != null) {
                ProjectResourcesUtil.executeProvider(writer, saveProjectAdvisor, null);
            } else {
                log.error("The project cannot be saved because the format is not available.");
                // use save as instead
                saveAs();
            }
        } else {
            saveAs();
        }
    } else {
        saveAs();
    }
}
Also used : IOProviderDescriptor(eu.esdihumboldt.hale.common.core.io.extension.IOProviderDescriptor) IOConfiguration(eu.esdihumboldt.hale.common.core.io.project.model.IOConfiguration) ProjectWriter(eu.esdihumboldt.hale.common.core.io.project.ProjectWriter) IOReport(eu.esdihumboldt.hale.common.core.io.report.IOReport) FileIOSupplier(eu.esdihumboldt.hale.common.core.io.supplier.FileIOSupplier) NoStreamOutputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.NoStreamOutputSupplier) ProjectFile(eu.esdihumboldt.hale.common.core.io.project.model.ProjectFile) File(java.io.File) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExecutionException(java.util.concurrent.ExecutionException)

Example 3 with NoStreamOutputSupplier

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

the class AbstractDBTest method writeInstances.

/**
 * Write instances to the database.
 *
 * @param instances the collection of instances
 * @param schema the target schema
 * @throws Exception if writing the instances fails
 */
protected void writeInstances(InstanceCollection instances, Schema schema) throws Exception {
    JDBCInstanceWriter writer = new JDBCInstanceWriter();
    writer.setTarget(new NoStreamOutputSupplier(jdbcUri));
    writer.setParameter(JDBCInstanceWriter.PARAM_USER, Value.of(dbi.getUser()));
    writer.setParameter(JDBCInstanceWriter.PARAM_PASSWORD, Value.of(dbi.getPassword()));
    writer.setInstances(instances);
    DefaultSchemaSpace targetSchema = new DefaultSchemaSpace();
    targetSchema.addSchema(schema);
    writer.setTargetSchema(targetSchema);
    IOReport report = writer.execute(null);
    assertTrue(report.isSuccess());
    assertTrue(report.getErrors().isEmpty());
}
Also used : DefaultSchemaSpace(eu.esdihumboldt.hale.common.schema.model.impl.DefaultSchemaSpace) IOReport(eu.esdihumboldt.hale.common.core.io.report.IOReport) NoStreamOutputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.NoStreamOutputSupplier) JDBCInstanceWriter(eu.esdihumboldt.hale.io.jdbc.JDBCInstanceWriter)

Aggregations

IOReport (eu.esdihumboldt.hale.common.core.io.report.IOReport)3 NoStreamOutputSupplier (eu.esdihumboldt.hale.common.core.io.supplier.NoStreamOutputSupplier)3 File (java.io.File)2 IOProviderConfigurationException (eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException)1 IOProviderDescriptor (eu.esdihumboldt.hale.common.core.io.extension.IOProviderDescriptor)1 ProjectWriter (eu.esdihumboldt.hale.common.core.io.project.ProjectWriter)1 IOConfiguration (eu.esdihumboldt.hale.common.core.io.project.model.IOConfiguration)1 Project (eu.esdihumboldt.hale.common.core.io.project.model.Project)1 ProjectFile (eu.esdihumboldt.hale.common.core.io.project.model.ProjectFile)1 MutableTargetIOReport (eu.esdihumboldt.hale.common.core.io.report.MutableTargetIOReport)1 FileIOSupplier (eu.esdihumboldt.hale.common.core.io.supplier.FileIOSupplier)1 LocatableURI (eu.esdihumboldt.hale.common.core.io.supplier.LocatableURI)1 DefaultSchemaSpace (eu.esdihumboldt.hale.common.schema.model.impl.DefaultSchemaSpace)1 HaleConnectException (eu.esdihumboldt.hale.io.haleconnect.HaleConnectException)1 HaleConnectProjectInfo (eu.esdihumboldt.hale.io.haleconnect.HaleConnectProjectInfo)1 Owner (eu.esdihumboldt.hale.io.haleconnect.Owner)1 OwnerType (eu.esdihumboldt.hale.io.haleconnect.OwnerType)1 JDBCInstanceWriter (eu.esdihumboldt.hale.io.jdbc.JDBCInstanceWriter)1 FileOutputStream (java.io.FileOutputStream)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1