use of eu.esdihumboldt.hale.common.core.io.project.model.Project 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;
}
use of eu.esdihumboldt.hale.common.core.io.project.model.Project in project hale by halestudio.
the class AbstractAppSchemaConfigurator method updateTargetSchemaResources.
// TODO: code adapted from ArchiveProjectWriter: how to avoid duplication?
private Map<URI, String> updateTargetSchemaResources(File targetDirectory, ProgressIndicator progress, IOReporter reporter) throws IOException {
progress.begin("Copy resources", ProgressIndicator.UNKNOWN);
Project project = (Project) getProjectInfo();
// resource locations mapped to new resource path
Map<URI, String> handledResources = new HashMap<>();
try {
List<IOConfiguration> resources = project.getResources();
// every resource needs his own directory
int count = 0;
Iterator<IOConfiguration> iter = resources.iterator();
while (iter.hasNext()) {
IOConfiguration resource = iter.next();
if (resource.getActionId().equals(SchemaIO.ACTION_LOAD_TARGET_SCHEMA)) {
// get resource path
Map<String, Value> providerConfig = resource.getProviderConfiguration();
String path = providerConfig.get(ImportProvider.PARAM_SOURCE).toString();
URI pathUri;
try {
pathUri = new URI(path);
} catch (URISyntaxException e1) {
reporter.error(new IOMessageImpl("Skipped resource because of invalid URI: " + path, e1));
continue;
}
// check if path was already handled
if (handledResources.containsKey(pathUri)) {
// skip copying the resource
continue;
}
String scheme = pathUri.getScheme();
LocatableInputSupplier<? extends InputStream> input = null;
if (scheme != null) {
if (scheme.equals("http") || scheme.equals("https") || scheme.equals("file") || scheme.equals("platform") || scheme.equals("bundle") || scheme.equals("jar")) {
input = new DefaultInputSupplier(pathUri);
} else {
continue;
}
} else {
// now can't open that, can we?
reporter.error(new IOMessageImpl("Skipped resource because it cannot be loaded from " + pathUri.toString(), null));
continue;
}
progress.setCurrentTask("Copying resource at " + path);
// every resource file is copied into an own resource
// directory in the target directory
String resourceFolder = "_schemas";
if (count > 0) {
resourceFolder += count;
}
File newDirectory = new File(targetDirectory, resourceFolder);
try {
newDirectory.mkdir();
} catch (SecurityException e) {
throw new IOException("Can not create directory " + newDirectory.toString(), e);
}
// the filename
String name = path.toString().substring(path.lastIndexOf("/") + 1, path.length());
// remove any query string from the filename
int queryIndex = name.indexOf('?');
if (queryIndex >= 0) {
name = name.substring(0, queryIndex);
}
if (name.isEmpty()) {
name = "file";
}
File newFile = new File(newDirectory, name);
Path target = newFile.toPath();
// retrieve the resource advisor
Value ct = providerConfig.get(ImportProvider.PARAM_CONTENT_TYPE);
IContentType contentType = null;
if (ct != null) {
contentType = HalePlatform.getContentTypeManager().getContentType(ct.as(String.class));
}
ResourceAdvisor ra = ResourceAdvisorExtension.getInstance().getAdvisor(contentType);
// copy the resource
progress.setCurrentTask("Copying resource at " + path);
ra.copyResource(input, target, contentType, true, reporter);
// store new path for resource
String newPath = resourceFolder + "/" + name;
handledResources.put(pathUri, newPath);
count++;
}
}
} finally {
progress.end();
}
return handledResources;
}
use of eu.esdihumboldt.hale.common.core.io.project.model.Project in project hale by halestudio.
the class AbstractProjectDetailsPage method updateConfiguration.
/**
* @see IOWizardPage#updateConfiguration(IOProvider)
*/
@Override
public boolean updateConfiguration(ProjectWriter provider) {
Project p = provider.getProject();
if (p != null) {
p.setName(name.getStringValue());
p.setAuthor(author.getStringValue());
p.setDescription((description.getText().isEmpty()) ? (null) : (description.getText()));
return true;
}
return false;
}
use of eu.esdihumboldt.hale.common.core.io.project.model.Project in project hale by halestudio.
the class ProjectParser method execute.
/**
* @see AbstractIOProvider#execute(ProgressIndicator, IOReporter)
*/
@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException {
progress.begin(Messages.ProjectParser_0, ProgressIndicator.UNKNOWN);
try {
File file;
try {
file = new File(getSource().getLocation());
} catch (IllegalArgumentException e) {
file = null;
}
String basePath = (file == null) ? (new File(".").getAbsolutePath()) : (FilenameUtils.getFullPath(file.getAbsolutePath()));
// Unmarshal the project file
JAXBContext jc;
JAXBElement<HaleProject> root;
try {
jc = JAXBContext.newInstance(PROJECT_CONTEXT, ObjectFactory.class.getClassLoader());
Unmarshaller u = jc.createUnmarshaller();
u.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
root = u.unmarshal(new StreamSource(getSource().getInput()), HaleProject.class);
} catch (JAXBException e) {
reporter.error(new IOMessageImpl("Unmarshalling the HaleProject from the given resource failed: {0}", e, -1, -1, getSource().getLocation()));
reporter.setSuccess(false);
return reporter;
}
project = new Project();
projectFiles = new HashMap<String, ProjectFile>();
report = reporter;
HaleProject haleProject = root.getValue();
// populate project and project files
loadProject(haleProject);
loadSchemas(haleProject, basePath);
loadAlignment(haleProject, basePath);
loadStyle(haleProject, basePath);
loadInstances(haleProject, basePath);
loadTasks(haleProject, basePath);
loadConfig(haleProject);
report = null;
reporter.setSuccess(true);
return reporter;
} finally {
progress.end();
}
}
use of eu.esdihumboldt.hale.common.core.io.project.model.Project in project hale by halestudio.
the class ArchiveProjectReader method execute.
@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException {
// copy resources to a temporary directory
tempDir = Files.createTempDir();
IOUtils.extract(tempDir, getSource().getInput());
// create the project file via XMLProjectReader
File baseFile = new File(tempDir, "project.halex");
ProjectReader reader;
if (!baseFile.exists()) {
// look for project file
log.debug("Default project file not found, looking for other candidates.");
String candidate = ProjectIO.findProjectFile(tempDir);
if (candidate != null) {
log.info(MessageFormat.format("Loading {0} as project file from archive", candidate));
baseFile = new File(tempDir, candidate);
}
reader = HaleIO.findIOProvider(ProjectReader.class, new FileIOSupplier(baseFile), candidate);
if (reader == null) {
reporter.error(new IOMessageImpl("Could not find reader for project file " + candidate, null));
reporter.setSuccess(false);
return reporter;
}
} else {
// default project file
reader = new XMLProjectReader();
}
LocatableInputSupplier<InputStream> tempSource = new FileIOSupplier(baseFile);
// save old save configuration
LocatableInputSupplier<? extends InputStream> oldSource = getSource();
setSource(tempSource);
reader.setSource(tempSource);
reader.setProjectFiles(getProjectFiles());
IOReport report = reader.execute(progress);
Project readProject = reader.getProject();
if (readProject != null) {
/*
* Because the original source is only available here, update the
* project's resource paths here.
*
* The only drawback is that the UILocationUpdater cannot be used.
*/
LocationUpdater updater = new LocationUpdater(readProject, tempSource.getLocation());
// update resources
// resources are made absolute (else they can't be found afterwards)
updater.updateProject(false);
}
// set the real source
setSource(oldSource);
// set the read project
setProjectChecked(readProject, reporter);
return report;
}
Aggregations