Search in sources :

Example 16 with Value

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;
}
Also used : Binding(groovy.lang.Binding) ParameterBinding(eu.esdihumboldt.hale.common.align.model.impl.mdexpl.ParameterBinding) Script(groovy.lang.Script) TransformationException(eu.esdihumboldt.hale.common.align.transformation.function.TransformationException) ParameterValue(eu.esdihumboldt.hale.common.align.model.ParameterValue) NoResultException(eu.esdihumboldt.hale.common.align.transformation.function.impl.NoResultException) GroovyService(eu.esdihumboldt.util.groovy.sandbox.GroovyService) PropertyValue(eu.esdihumboldt.hale.common.align.transformation.function.PropertyValue) Value(eu.esdihumboldt.hale.common.core.io.Value) ParameterValue(eu.esdihumboldt.hale.common.align.model.ParameterValue) InstanceBuilder(eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)

Example 17 with Value

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;
}
Also used : Value(eu.esdihumboldt.hale.common.core.io.Value) Text(eu.esdihumboldt.hale.common.core.io.Text)

Example 18 with Value

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;
}
Also used : Path(java.nio.file.Path) DefaultInputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.DefaultInputSupplier) HashMap(java.util.HashMap) IOConfiguration(eu.esdihumboldt.hale.common.core.io.project.model.IOConfiguration) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl) IContentType(org.eclipse.core.runtime.content.IContentType) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) ResourceAdvisor(eu.esdihumboldt.hale.common.core.io.ResourceAdvisor) Project(eu.esdihumboldt.hale.common.core.io.project.model.Project) Value(eu.esdihumboldt.hale.common.core.io.Value) File(java.io.File)

Example 19 with Value

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;
}
Also used : Group(eu.esdihumboldt.hale.common.instance.model.Group) DefaultInstance(eu.esdihumboldt.hale.common.instance.model.impl.DefaultInstance) MultiValue(eu.esdihumboldt.cst.MultiValue) PropertyValue(eu.esdihumboldt.hale.common.align.transformation.function.PropertyValue) Value(eu.esdihumboldt.hale.common.core.io.Value) MutableInstance(eu.esdihumboldt.hale.common.instance.model.MutableInstance) TypeDefinition(eu.esdihumboldt.hale.common.schema.model.TypeDefinition)

Example 20 with 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);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Category(eu.esdihumboldt.hale.common.align.extension.category.Category) StreamResult(javax.xml.transform.stream.StreamResult) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) Element(org.w3c.dom.Element) FunctionParameterDefinition(eu.esdihumboldt.hale.common.align.extension.function.FunctionParameterDefinition) Callable(java.util.concurrent.Callable) URL(java.net.URL) StringWriter(java.io.StringWriter) Value(eu.esdihumboldt.hale.common.core.io.Value)

Aggregations

Value (eu.esdihumboldt.hale.common.core.io.Value)81 ValueList (eu.esdihumboldt.hale.common.core.io.ValueList)12 LookupTable (eu.esdihumboldt.hale.common.lookup.LookupTable)12 HashMap (java.util.HashMap)12 ValueProperties (eu.esdihumboldt.hale.common.core.io.ValueProperties)11 LookupTableImpl (eu.esdihumboldt.hale.common.lookup.impl.LookupTableImpl)11 IOConfiguration (eu.esdihumboldt.hale.common.core.io.project.model.IOConfiguration)10 ParameterValue (eu.esdihumboldt.hale.common.align.model.ParameterValue)9 ArrayList (java.util.ArrayList)9 URI (java.net.URI)8 Test (org.junit.Test)6 StyledString (org.eclipse.jface.viewers.StyledString)5 Composite (org.eclipse.swt.widgets.Composite)5 DefaultCustomPropertyFunction (eu.esdihumboldt.hale.common.align.custom.DefaultCustomPropertyFunction)4 PropertyValue (eu.esdihumboldt.hale.common.align.transformation.function.PropertyValue)4 IOMessageImpl (eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl)4 TypeDefinition (eu.esdihumboldt.hale.common.schema.model.TypeDefinition)4 ProjectService (eu.esdihumboldt.hale.ui.service.project.ProjectService)4 IOException (java.io.IOException)4 Locale (java.util.Locale)4