use of eu.esdihumboldt.hale.common.core.io.Value in project hale by halestudio.
the class CustomGroovyTransformation method evaluate.
@Override
protected Object evaluate(String transformationIdentifier, TransformationEngine engine, ListMultimap<String, PropertyValue> variables, String resultName, PropertyEntityDefinition resultProperty, Map<String, String> executionParameters, TransformationLog log) throws TransformationException, NoResultException {
// store script as parameter
if (!CustomPropertyFunctionType.GROOVY.equals(customFunction.getFunctionType())) {
throw new TransformationException("Custom function is not of type groovy");
}
Value scriptValue = customFunction.getFunctionDefinition();
if (scriptValue.isEmpty()) {
throw new NoResultException("Script not defined");
}
ListMultimap<String, ParameterValue> params = ArrayListMultimap.create();
params.put(GroovyTransformation.PARAMETER_SCRIPT, new ParameterValue(scriptValue));
setParameters(params);
// instance builder
InstanceBuilder builder = GroovyTransformation.createBuilder(resultProperty);
// create the script binding
Binding binding = createGroovyBinding(variables, getCell(), getTypeCell(), builder, log, getExecutionContext(), resultProperty.getDefinition().getPropertyType());
Object result;
try {
GroovyService service = getExecutionContext().getService(GroovyService.class);
Script groovyScript = GroovyUtil.getScript(this, binding, service, true);
// evaluate the script
result = GroovyTransformation.evaluate(groovyScript, builder, resultProperty.getDefinition().getPropertyType(), service, log);
} catch (TransformationException | NoResultException e) {
throw e;
} catch (Throwable e) {
throw new TransformationException("Error evaluating the custom function script", e);
}
if (result == null) {
throw new NoResultException();
}
return result;
}
use of eu.esdihumboldt.hale.common.core.io.Value in project hale by halestudio.
the class GroovyExplanation method getScript.
/**
* Get the script stored in a Groovy function cell.
*
* @param cell the cell
* @return the Groovy script string or <code>null</code>
*/
public static String getScript(Cell cell) {
Value scriptValue = CellUtil.getFirstParameter(cell, PARAMETER_SCRIPT);
String script;
// try retrieving as text
Text text = scriptValue.as(Text.class);
if (text != null) {
script = text.getText();
} else {
// fall back to string value
script = scriptValue.as(String.class);
}
return script;
}
use of eu.esdihumboldt.hale.common.core.io.Value 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.Value in project hale by halestudio.
the class FunctionExecutor method processValue.
/**
* Processes the given value. Does not handle {@link MultiValue}!
*
* @param cellLog the transformation log
* @param function the property function
* @param value the value to process
* @param node the target node
* @return the processed value
*/
private Object processValue(TransformationLog cellLog, PropertyTransformation<?> function, Object value, TargetNode node) {
if (function.allowAutomatedResultConversion()) {
if (!(value instanceof Group)) {
// convert value for target
try {
value = convert(value, toPropertyEntityDefinition(node.getEntityDefinition()));
} catch (Throwable e) {
// ignore, but create error
cellLog.error(cellLog.createMessage("Conversion according to target property failed, using value as is.", e));
}
} else {
// TODO any conversion necessary/possible
}
} else {
// unwrap value
if (value instanceof Value) {
value = ((Value) value).getValue();
}
}
/*
* If the value is no group, but it should be one, create an instance
* wrapping the value
*/
TypeDefinition propertyType = toPropertyEntityDefinition(node.getEntityDefinition()).getDefinition().getPropertyType();
if (!(value instanceof Group) && !propertyType.getChildren().isEmpty()) {
MutableInstance instance = new DefaultInstance(propertyType, null);
instance.setValue(value);
value = instance;
}
return value;
}
use of eu.esdihumboldt.hale.common.core.io.Value in project hale by halestudio.
the class FunctionReferenceContent method getFunctionContent.
private InputStream getFunctionContent(String func_id) throws Exception {
// maps "function" to the real function ID (used by the template)
final FunctionDefinition<?> function = FunctionUtil.getFunction(func_id, null);
if (function == null) {
log.warn("Unknown function " + func_id);
return null;
}
Callable<VelocityContext> contextFactory = new Callable<VelocityContext>() {
@Override
public VelocityContext call() throws Exception {
VelocityContext context = new VelocityContext();
context.put("showImage", imageContentMethod != null);
context.put("function", function);
// Map<paramDisplayName, sampleDataStringRepresentation>
Map<String, String> parameterDocu = new HashMap<String, String>();
for (FunctionParameterDefinition param : function.getDefinedParameters()) {
if (param.getValueDescriptor() != null && param.getValueDescriptor().getSampleData() != null) {
Value sample = param.getValueDescriptor().getSampleData();
if (sample.isRepresentedAsDOM()) {
// get DOM Element as String
Element ele = sample.getDOMRepresentation();
StringWriter writer = new StringWriter();
StreamResult formattedXmlString = new StreamResult(writer);
XmlUtil.prettyPrint(new DOMSource(ele), formattedXmlString);
// escape special chars to display xml code on html
String xmlString = formattedXmlString.getWriter().toString();
xmlString = StringEscapeUtils.escapeXml(xmlString);
parameterDocu.put(param.getDisplayName(), xmlString);
} else {
parameterDocu.put(param.getDisplayName(), sample.getStringRepresentation());
}
}
}
context.put("parameterDocu", parameterDocu);
if (function.getCategoryId() != null) {
String categoryId = function.getCategoryId();
Category category = (CategoryExtension.getInstance().get(categoryId));
// String category = categoryId.substring(categoryId
// .lastIndexOf(".") + 1);
//
// category = capitalize(category);
context.put("category", category);
}
// creating path for the file to be included
URL help_url = function.getHelpURL();
if (help_url != null) {
String help_path = help_url.getPath();
String bundle = function.getDefiningBundle();
StringBuffer sb_include = new StringBuffer();
sb_include.append(bundle);
sb_include.append(help_path);
sb_include.append("/help");
String final_help_url = sb_include.toString();
context.put("include", final_help_url);
}
return context;
}
};
return getContentFromTemplate(func_id, "function", contextFactory);
}
Aggregations