]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling/src/org/simantics/modeling/userComponent/ComponentTypeCommands.java
Merge changes I78c3a258,I7bf72f04
[simantics/platform.git] / bundles / org.simantics.modeling / src / org / simantics / modeling / userComponent / ComponentTypeCommands.java
1 /*******************************************************************************
2  * Copyright (c) 2012 Association for Decentralized Information Management in
3  * Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.modeling.userComponent;
13
14 import java.util.Collections;
15 import java.util.Map;
16
17 import org.simantics.databoard.Bindings;
18 import org.simantics.databoard.Datatypes;
19 import org.simantics.databoard.adapter.AdaptException;
20 import org.simantics.databoard.binding.Binding;
21 import org.simantics.databoard.binding.error.BindingException;
22 import org.simantics.databoard.parser.repository.DataTypeSyntaxError;
23 import org.simantics.databoard.parser.repository.DataValueRepository;
24 import org.simantics.databoard.type.Datatype;
25 import org.simantics.databoard.type.NumberType;
26 import org.simantics.db.ReadGraph;
27 import org.simantics.db.Resource;
28 import org.simantics.db.Statement;
29 import org.simantics.db.WriteGraph;
30 import org.simantics.db.common.CommentMetadata;
31 import org.simantics.db.common.request.EnumerationMap;
32 import org.simantics.db.common.request.IsEnumeratedValue;
33 import org.simantics.db.common.request.UnaryRead;
34 import org.simantics.db.common.utils.NameUtils;
35 import org.simantics.db.exception.DatabaseException;
36 import org.simantics.db.exception.ServiceException;
37 import org.simantics.db.layer0.QueryIndexUtils;
38 import org.simantics.db.layer0.util.Layer0Utils;
39 import org.simantics.layer0.Layer0;
40 import org.simantics.modeling.ModelingResources;
41 import org.simantics.modeling.NewSymbol;
42 import org.simantics.operation.Layer0X;
43 import org.simantics.scl.runtime.tuple.Tuple;
44 import org.simantics.scl.runtime.tuple.Tuple3;
45 import org.simantics.selectionview.SelectionViewResources;
46 import org.simantics.structural.stubs.StructuralResource2;
47 import org.simantics.structural2.utils.StructuralUtils;
48 import org.simantics.utils.strings.AlphanumComparator;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 import gnu.trove.map.hash.THashMap;
53
54 public class ComponentTypeCommands {
55
56     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentTypeCommands.class);
57
58     public static void applyCode(WriteGraph g, Resource componentType, String code) throws DatabaseException {
59         StructuralResource2 STR = StructuralResource2.getInstance(g);
60         g.claimLiteral(componentType, STR.ProceduralComponentType_code, code, Bindings.STRING);
61     }
62
63     public static Resource createConnectionPoint(WriteGraph g, Resource componentType, Resource cp) throws DatabaseException {
64         return StructuralUtils.createConnectionPoint(g, componentType, cp);
65     }
66
67     public static Resource createMonitorPropertyWithDefaults(WriteGraph g, Resource componentType) throws DatabaseException {
68
69         Layer0 L0 = Layer0.getInstance(g);
70         StructuralResource2 STR = StructuralResource2.getInstance(g);
71         ModelingResources MOD = ModelingResources.getInstance(g);
72
73         Resource monitorType = g.getPossibleObject(componentType, STR.ComponentType_HasDefaultMonitorValueType);
74         if(monitorType == null) monitorType = MOD.MonitorValue;
75
76         Resource relation = createPropertyWithDefaultsBase(g, componentType, "newProperty");
77         g.claim(relation, L0.HasRange, monitorType);
78
79         Resource assertion = g.newResource();
80         g.claim(componentType, L0.Asserts, assertion);
81         g.claim(assertion, L0.InstanceOf, L0.Assertion);
82         g.claim(assertion, L0.HasPredicate, relation);
83         
84         Resource value = g.newResource();
85         g.claim(value, L0.InstanceOf, monitorType);
86         g.claimLiteral(value, L0.HasValueType, L0.String, "Double", Bindings.STRING);
87         g.claimLiteral(value, L0.SCLValue_expression, L0.String, "", Bindings.STRING);
88         g.claim(assertion, L0.HasObject, value);
89         
90         return relation;
91         
92     }
93
94     public static Resource createPropertyWithDefaults(WriteGraph g, Resource componentType) throws DatabaseException {
95         g.markUndoPoint();
96         Layer0 L0 = Layer0.getInstance(g);
97
98         Resource relation = createPropertyWithDefaultsBase(g, componentType, "newProperty");
99
100         Resource assertion = g.newResource();
101         g.claim(componentType, L0.Asserts, assertion);
102         g.claim(assertion, L0.InstanceOf, L0.Assertion);
103         g.claim(assertion, L0.HasPredicate, relation);
104         
105         Resource value = g.newResource();
106         g.claim(value, L0.InstanceOf, L0.Literal);
107         g.claimLiteral(value, L0.HasDataType, L0.DataType, Datatypes.DOUBLE, Bindings.getBindingUnchecked(Datatype.class));
108         g.claimLiteral(value, L0.HasValueType, L0.String, "Double", Bindings.STRING);
109         g.claimValue(value, 0.0, Bindings.DOUBLE);
110         g.claim(assertion, L0.HasObject, value);
111         
112         return relation;
113         
114     }
115
116     public static Resource createPropertyWithDefaultsBase(WriteGraph g, Resource componentType, String defaultName) throws DatabaseException {
117
118         Layer0 L0 = Layer0.getInstance(g);
119         StructuralResource2 STR = StructuralResource2.getInstance(g);
120         ModelingResources MOD = ModelingResources.getInstance(g);
121
122         String name = NameUtils.findFreshEscapedName(g, defaultName, componentType);
123
124         Resource relation = g.newResource();
125         g.claim(relation, L0.SubrelationOf, null, L0.HasProperty);
126         boolean hadProperty = false;
127         for(Resource type : g.getObjects(componentType, STR.ComponentType_HasDefaultPropertyRelationType)) {
128                 if(g.isInheritedFrom(type, STR.Property)) hadProperty = true;
129             g.claim(relation, L0.InstanceOf, type);
130         }
131         if(!hadProperty)
132                 g.claim(relation, L0.InstanceOf, STR.Property);
133         
134         g.claimLiteral(relation, L0.HasName, name);
135         g.claim(componentType, L0.ConsistsOf, L0.PartOf, relation);
136         g.claim(relation, L0.HasDomain, L0.DomainOf, componentType);
137
138         Resource invRelation = g.newResource();
139         g.claim(invRelation, L0.SubrelationOf, null, L0.PropertyOf);
140         g.claim(relation, L0.ConsistsOf, L0.PartOf, invRelation);
141         g.claimLiteral(invRelation, L0.HasName, "Inverse");
142         g.claim(relation, L0.InverseOf, invRelation);
143
144         g.claimLiteral(relation, L0.RequiresValueType, "Double");
145
146         SelectionViewResources SEL = SelectionViewResources.getInstance(g);
147         Resource category = g.getPossibleObject(relation, SEL.HasStandardPropertyInfo);
148         if(category == null) {
149                 g.claim(relation, SEL.HasStandardPropertyInfo, MOD.UserDefinedPropertyInfo);
150         }
151         if(!g.isInstanceOf(relation, SEL.GenericParameterType))
152                 g.claim(relation, L0.InstanceOf, SEL.GenericParameterType);
153         
154         CommentMetadata cm = g.getMetadata(CommentMetadata.class);
155         g.addMetadata(cm.add("Created new property " + name + " for " + g.getRelatedValue2(componentType, L0.HasName, Bindings.STRING) + " " + componentType.toString()));
156
157         return relation;
158     }
159     
160     public static Resource createProperty(WriteGraph graph, Resource componentType, String name, String type, String unit, String range, String label, String description) throws DatabaseException {
161         
162         Resource property = createPropertyWithDefaults(graph, componentType);
163         rename(graph, property, name);
164         setRequiredType(graph, componentType, property, type);
165         convertDefaultValue(graph, componentType, property, type);
166         //setDefaultValue(graph, type, relation, valueText)
167         if (!type.equals("String")) {
168                 setUnit(graph, componentType, property, unit);
169                 setRange(graph, componentType, property, range);        
170         }
171         setLabel(graph, property, label);
172         setDescription(graph, property, description);
173         
174         return property;
175     }
176
177     public static void removeProperty(WriteGraph g, Resource componentType, Resource property) throws DatabaseException {
178         Layer0 L0 = Layer0.getInstance(g);
179         for(Resource assertion : g.getObjects(property, L0.HasPredicateInverse))
180             g.deny(assertion);
181         g.deny(property);
182         
183         String name = g.getPossibleRelatedValue2(componentType, L0.HasName);
184         
185         CommentMetadata cm = g.getMetadata(CommentMetadata.class);
186         g.addMetadata(cm.add("Removed property " + property + " from component/annotation " + name + ", resource "+ componentType));
187     }
188
189     public static void rename(WriteGraph g, Resource resource, String newName) throws DatabaseException {
190         Layer0 L0 = Layer0.getInstance(g);
191         
192         String prevName = g.getPossibleRelatedValue2(resource, L0.HasName);
193         g.claimLiteral(resource, L0.HasName, newName);
194         
195         CommentMetadata cm = g.getMetadata(CommentMetadata.class);
196         g.addMetadata(cm.add("Renamed component/annotation type from " + prevName + " to " + newName + ", resource " + resource  ));
197     }
198
199     public static void setRequiredType(WriteGraph g, Resource property,
200             String requiredType) throws DatabaseException {
201         setRequiredType(g, null, property, requiredType);
202     }
203
204     public static void setRequiredType(WriteGraph g, Resource componentType, Resource property,
205             String requiredType) throws DatabaseException {
206         setRequiredType(g, componentType, property, requiredType, null);
207     }
208
209     public static void setRequiredType(WriteGraph g, Resource componentType, Resource property,
210             String requiredType, Resource possibleType) throws DatabaseException {
211         Layer0 L0 = Layer0.getInstance(g);
212         g.claimLiteral(property, L0.RequiresValueType, requiredType);
213
214         if (componentType != null) {
215             StructuralResource2 STR = StructuralResource2.getInstance(g);
216             for (Resource assertedValue : g.getAssertedObjects(componentType, property)) {
217                 if (g.isInstanceOf(assertedValue, STR.MonitorValue)) {
218                     g.claimLiteral(assertedValue, L0.HasValueType, requiredType);
219                 }
220             }
221         }
222
223         // We assert the range of the property only if we are given a dedicated graph value type
224         if(g.hasStatement(property, L0.HasRange))
225             g.deny(property, L0.HasRange);
226
227         if(possibleType != null) {
228             // We have a dedicated graph type for this SCL value type
229             if(g.hasStatement(possibleType, L0.Enumeration)) {
230                 // This value type is an enumeration - let's constrain the range of this predicate to match the enumeration type only
231                 g.claim(property, L0.HasRange, possibleType);
232             }
233         }
234
235         CommentMetadata cm = g.getMetadata(CommentMetadata.class);
236         g.addMetadata(cm.add("Set required type "+ requiredType + " for component/annotation " + property));
237     }
238     
239     public static void editType(WriteGraph graph, Resource componentType, Resource property, boolean convertDefaultValue, String newValue) throws DatabaseException {
240         editType(graph, componentType, property, convertDefaultValue, newValue, null);
241     }
242
243     public static void editType(WriteGraph graph, Resource componentType, Resource property, boolean convertDefaultValue, String newValue, Resource possibleType) throws DatabaseException {
244         ComponentTypeCommands.setRequiredType(graph, componentType, property, newValue, possibleType);
245         if (convertDefaultValue) {
246             ComponentTypeCommands.convertDefaultValue(graph, componentType, property, newValue, possibleType);
247             for (Resource indexRoot : Layer0Utils.listIndexRoots(graph)) {
248                 for(Resource instance : QueryIndexUtils.searchByTypeShallow(graph, indexRoot, componentType)) {
249                     ComponentTypeCommands.convertInstantiatedValue(graph, instance, property, newValue, componentType);
250                 }
251             }
252         }
253     }
254
255     static class AssertionMap extends UnaryRead<Resource, Map<Resource,Resource>> {
256         public AssertionMap(Resource parameter) {
257             super(parameter);
258         }
259
260         @Override
261         public Map<Resource, Resource> perform(ReadGraph graph)
262                 throws DatabaseException {
263             THashMap<Resource,Resource> result = new THashMap<Resource, Resource>();
264             Layer0 L0 = Layer0.getInstance(graph);
265             for(Resource assertion : graph.getObjects(parameter, L0.Asserts))
266                 result.put(graph.getSingleObject(assertion, L0.HasPredicate), 
267                         graph.getSingleObject(assertion, L0.HasObject));
268             return result;
269         }
270     }
271
272     public static Resource getAssertedObject(ReadGraph g, Resource type, Resource relation) throws DatabaseException {
273         return g.syncRequest(new AssertionMap(type)).get(relation);
274     }
275
276     public static void setMonitorExpression(WriteGraph g, Resource type, Resource relation,
277             String valueText) throws DatabaseException {
278
279         Resource object = getAssertedObject(g, type, relation);
280         if(object == null) {
281             LOGGER.warn("Didn't find assertion for " + NameUtils.getSafeName(g, relation) + 
282                     " in " + NameUtils.getSafeName(g, type) + ".");
283             return;
284         }
285         Layer0 L0 = Layer0.getInstance(g);
286         g.claimLiteral(object, L0.SCLValue_expression, valueText, Bindings.STRING);
287         
288     }
289
290     public static void setDefaultValue(WriteGraph g, Resource type, Resource relation,
291             String valueText) throws DatabaseException {
292
293         Resource object = getAssertedObject(g, type, relation);
294         if(object == null) {
295             LOGGER.warn("Didn't find assertion for " + NameUtils.getSafeName(g, relation) + 
296                     " in " + NameUtils.getSafeName(g, type) + ".");
297             return;
298         }
299
300         Layer0 L0 = Layer0.getInstance(g);
301         Resource range = g.getPossibleObject(relation, L0.HasRange);
302         if (range != null) {
303             if(g.hasStatement(range, L0.Enumeration)) {
304                 Map<String,Resource> values = g.syncRequest(new EnumerationMap(range));
305                 Resource value = values.get(valueText);
306                 if (value != null) {
307                     for(Resource assertion : g.getObjects(type, L0.Asserts)) {
308                         Resource p = g.getSingleObject(assertion, L0.HasPredicate);
309                         if (p.equals(relation)) {
310                             g.deny(assertion, L0.HasObject, object);
311                             g.claim(assertion, L0.HasObject, value);
312                         }
313                     }
314                 }
315                 return;
316             }
317         }
318         
319         if(valueText.length() > 0 && valueText.charAt(0) == '=') {
320                 
321                 String expression = valueText.substring(1);
322                 ModelingResources MOD = ModelingResources.getInstance(g);
323                 if(!g.isInstanceOf(object, MOD.SCLValue)) {
324                         Resource assertion = g.getSingleObject(object, L0.HasObjectInverse);
325                         g.deny(assertion, L0.HasObject, object);
326                         object = g.newResource();
327                         g.claim(object, L0.InstanceOf, MOD.SCLValue);
328                         g.claim(assertion, L0.HasObject, object);
329                 }
330                 g.claimLiteral(object, L0.SCLValue_expression, L0.String, expression, Bindings.STRING);
331             Layer0Utils.addCommentMetadata(g, "Modified " + g.getRelatedValue2(relation, Layer0.getInstance(g).HasName, Bindings.STRING) + " with new expression '" + expression + "'");
332             
333         } else {
334                 
335                 ModelingResources MOD = ModelingResources.getInstance(g);
336                 if(g.isInstanceOf(object, MOD.SCLValue)) {
337                         Resource assertion = g.getSingleObject(object, L0.HasObjectInverse);
338                         g.deny(assertion, L0.HasObject, object);
339                         object = g.newResource();
340                         String sclType = g.getRelatedValue(relation, L0.RequiresValueType, Bindings.STRING);
341                 Datatype newDatatype = TypeConversion.convertSCLTypeToDatatype(sclType);
342                         g.claim(object, L0.InstanceOf, L0.Literal);
343                 Binding ntb = Bindings.getBindingUnchecked(Datatype.class);
344                 g.claimLiteral(object, L0.HasDataType, L0.DataType, newDatatype, ntb);
345                         g.claim(assertion, L0.HasObject, object);
346                 }
347                 
348                 Datatype dt = g.getDataType(object);
349                 Binding binding = Bindings.getBinding(dt);
350                 Object value;
351                 try {
352                         value = binding.parseValue(valueText, new DataValueRepository());
353                         g.claimValue(object, value, binding);
354                         Layer0Utils.addCommentMetadata(g, "Modified " + g.getRelatedValue2(relation, Layer0.getInstance(g).HasName, Bindings.STRING) + " with new value " + value.toString());
355                 } catch (DataTypeSyntaxError e) {
356                         e.printStackTrace();
357                 } catch (BindingException e) {
358                         e.printStackTrace();
359                 }
360                 
361         }
362
363     }
364
365     /**
366      * @param graph graph write transaction handle
367      * @param type component type to edit
368      * @param relation component type property relation to edit
369      * @param unit <code>null</code> to remove unit description
370      * @throws DatabaseException
371      */
372     public static void setUnit(WriteGraph graph, Resource type, Resource relation, String unit) throws DatabaseException {
373         Resource object = getAssertedObject(graph, type, relation);
374         if (object == null) {
375             LOGGER.warn("Didn't find assertion for " + NameUtils.getSafeName(graph, relation) + 
376                     " in " + NameUtils.getSafeName(graph, type) + ".");
377             return;
378         }
379
380         Layer0 L0 = Layer0.getInstance(graph);
381         Layer0X L0X = Layer0X.getInstance(graph);
382         boolean hasRequiresDataType = graph.hasStatement(relation, L0X.RequiresDataType);
383         if (hasRequiresDataType) {
384             Datatype dt = graph.getDataType(object);
385             if (dt instanceof NumberType) {
386                 NumberType nt = (NumberType) Bindings.DATATYPE.cloneUnchecked(dt);
387                 nt.setUnit(unit);
388                 graph.claimLiteral(object, L0.HasDataType, L0.DataType, nt, Bindings.DATATYPE);
389                 graph.claimLiteral(relation, L0X.RequiresDataType, L0.DataType, nt, Bindings.DATATYPE);
390             }
391         }
392
393         String oldUnit = graph.getPossibleRelatedValue2(relation, L0X.HasUnit, Bindings.STRING);
394         if (unit != null) {
395             graph.claimLiteral(relation, L0X.HasUnit, L0.String, unit, Bindings.STRING);
396         } else {
397             graph.denyValue(relation, L0X.HasUnit);
398         }
399
400         CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
401         graph.addMetadata(cm.add("Set unit from " + oldUnit + " to " + unit + " for component/annotation " + type + " property " + relation));
402     }
403
404     /**
405      * @param graph graph write transaction handle
406      * @param type component type to modify
407      * @param relation property relation of a component type
408      * @param newRange new range definition or <code>null</code> to remove range restriction
409      * @throws DatabaseException 
410      */
411     public static void setRange(WriteGraph graph, Resource type, Resource relation, String newRange) throws DatabaseException {
412         Resource object = getAssertedObject(graph, type, relation);
413         if (object == null) {
414             LOGGER.warn("Didn't find assertion for " + NameUtils.getSafeName(graph, relation) + 
415                     " in " + NameUtils.getSafeName(graph, type) + ".");
416             return;
417         }
418
419         Datatype dt = graph.getDataType(object);
420         if (dt instanceof NumberType) {
421             NumberType nt = (NumberType) dt;
422             Binding ntb = Bindings.getBindingUnchecked(Datatype.class);
423             nt.setRange(newRange);
424
425             Layer0 L0 = Layer0.getInstance(graph);
426             Layer0X L0X = Layer0X.getInstance(graph);
427
428             graph.claimLiteral(object, L0.HasDataType, L0.DataType, nt, ntb);
429             graph.claimLiteral(relation, L0X.RequiresDataType, L0.DataType, nt, ntb);
430             
431             CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
432             graph.addMetadata(cm.add("Setted range " + newRange + " for component/annotation " + type));
433         }
434     }
435
436     public static Tuple getDatatypeValueAndBinding(ReadGraph g, Resource object, String newSCLType) throws DatabaseException {
437
438         Datatype newDatatype = TypeConversion.convertSCLTypeToDatatype(newSCLType);
439         if(newDatatype == null) {
440             LOGGER.warn("Couldn't convert default value to <" + newSCLType + ">.");
441             return null;
442         }
443         Binding newBinding = Bindings.getBinding(newDatatype);
444
445         Datatype oldDatatype = g.getDataType(object);
446         Binding oldBinding = Bindings.getBinding(oldDatatype);
447
448         Object oldValue = g.getValue(object, oldBinding);
449         Object newValue;
450         try {
451             newValue = Bindings.adapt(oldValue, oldBinding, newBinding);
452         } catch (AdaptException e) {
453             try {
454                 newValue = newBinding.createDefault();
455             } catch (BindingException e1) {
456                 e1.printStackTrace();
457                 return null;
458             }
459         }
460
461         return new Tuple3(newDatatype, newValue, newBinding);
462
463     }
464
465     public static void convertDefaultValue(WriteGraph g,
466             Resource type, Resource relation, String newSCLType) throws DatabaseException {
467         convertDefaultValue(g, type, relation, newSCLType, null);
468     }
469
470     private static Resource findAssertionWithPO(ReadGraph graph, Resource possibleType, Resource predicate, Resource object) throws DatabaseException {
471             Layer0 L0 = Layer0.getInstance(graph);
472         for(Resource assertion : graph.getObjects(possibleType, L0.Asserts)) {
473             Resource p = graph.getSingleObject(assertion, L0.HasPredicate);
474             Resource o = graph.getSingleObject(assertion, L0.HasObject);
475             if(predicate.equals(p) && object.equals(o))
476                 return assertion;
477         }
478         return null;
479     }
480
481     public static void convertDefaultValue(WriteGraph g,
482             Resource type, Resource relation, String newSCLType, Resource possibleType) throws DatabaseException {
483         Resource object = getAssertedObject(g, type, relation);
484         if(object == null) {
485             LOGGER.warn("Didn't find assertion for " + NameUtils.getSafeName(g, relation) + 
486                     " in " + NameUtils.getSafeName(g, type) + ".");
487             return;
488         }
489
490         Layer0 L0 = Layer0.getInstance(g);
491         if(possibleType != null) {
492             if(g.hasStatement(possibleType, L0.Enumeration)) {
493                 if(!g.isInstanceOf(object, possibleType)) {
494                     Map<String, Resource> enumMap = g.syncRequest(new EnumerationMap(possibleType));
495                     String firstKey = Collections.min(enumMap.keySet(), AlphanumComparator.COMPARATOR);
496                     Resource defaultValue = enumMap.get(firstKey);
497
498                     if (defaultValue != null) {
499                         Resource assertion = findAssertionWithPO(g, type, relation, object);
500                         if(assertion != null) {
501                             g.deny(assertion, L0.HasObject);
502                             g.claim(assertion, L0.HasObject, defaultValue);
503                             return;
504                         } else {
505                             Layer0Utils.assert_(g, type, relation, defaultValue);
506                             return;
507                         }
508                     }
509                 } else {
510                         return;
511                 }
512             }
513         }
514
515         Tuple tuple = getDatatypeValueAndBinding(g, object, newSCLType);
516         if (tuple == null)
517             return;
518
519         if(g.sync(new IsEnumeratedValue(object))) {
520             Resource assertion = findAssertionWithPO(g, type, relation, object);
521             object = g.newResource();
522             g.claim(object, L0.InstanceOf, L0.Literal);
523             if(assertion != null) {
524                 g.deny(assertion, L0.HasObject);
525                 g.claim(assertion, L0.HasObject, object);
526             }
527         }
528
529         g.claimLiteral(object, L0.HasDataType, L0.DataType, tuple.get(0), Bindings.getBindingUnchecked(Datatype.class));
530         g.claimLiteral(object, L0.HasValueType, g.<String>getRelatedValue(relation, L0.RequiresValueType, Bindings.STRING), Bindings.STRING);
531         g.claimValue(object, tuple.get(1), (Binding)tuple.get(2));
532
533     }
534
535     public static void convertInstantiatedValue(WriteGraph g, Resource instance, Resource relation, String newSCLType) throws DatabaseException {
536         convertInstantiatedValue(g, instance, relation, newSCLType, null);
537     }
538
539     public static void convertInstantiatedValue(WriteGraph g, Resource instance, Resource relation, String newSCLType, Resource possibleType)
540             throws DatabaseException {
541
542         Statement stm = g.getPossibleStatement(instance, relation);
543         if(stm != null && !stm.isAsserted(instance)) {
544
545             Layer0 L0 = Layer0.getInstance(g);
546             Resource object = stm.getObject();
547
548             if(g.sync(new IsEnumeratedValue(object))) {
549                 if(!g.isInstanceOf(object, possibleType)) {
550                     g.deny(instance, relation);
551                 }
552                 return;
553             }
554
555             // We can only convert literals
556             if(!g.isInstanceOf(object, L0.Literal)) return;
557
558             Tuple tuple = getDatatypeValueAndBinding(g, object, newSCLType);
559
560             g.claimLiteral(object, L0.HasDataType, L0.DataType, tuple.get(0), Bindings.getBindingUnchecked(Datatype.class));
561             g.claimLiteral(object, L0.HasValueType, g.<String>getRelatedValue(relation, L0.RequiresValueType, Bindings.STRING), Bindings.STRING);
562             g.claimValue(object, tuple.get(1), (Binding)tuple.get(2));
563
564         }
565
566     }
567
568     /**
569      * @param graph graph write transaction handle
570      * @param relation component type property relation to edit
571      * @param newDescription new label or <code>null</code> to remove label
572      * @throws DatabaseException 
573      */
574     public static void setLabel(WriteGraph graph, Resource relation, String newLabel) throws DatabaseException {
575         setProperty(graph, relation, Layer0.getInstance(graph).HasLabel, newLabel);
576         
577         CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
578         graph.addMetadata(cm.add("Setted label " + newLabel + " for component/annotation " + relation));
579     }
580
581     /**
582      * @param graph graph write transaction handle
583      * @param relation component type property relation to edit
584      * @param newDescription new description or <code>null</code> if new description
585      * @throws DatabaseException 
586      */
587     public static void setDescription(WriteGraph graph, Resource relation, String newDescription) throws DatabaseException {
588         setProperty(graph, relation, Layer0.getInstance(graph).HasDescription, newDescription);        
589         CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
590         graph.addMetadata(cm.add("Setted description " + newDescription + " for component/annotation " + relation));
591     }
592
593     /**
594      * @param graph graph write transaction handle
595      * @param relation component type property relation to edit
596      * @param newValue new property value or <code>null</code> to remove property
597      * @throws DatabaseException 
598      */
599     public static void setProperty(WriteGraph graph, Resource relation, Resource property, String newValue) throws DatabaseException {
600         if (newValue != null) {
601             graph.claimLiteral(relation, property, newValue, Bindings.STRING);
602         } else {
603             graph.denyValue(relation, property);
604         }
605     }
606
607     /**
608      * @param graph
609      * @param componentType
610      * @return the created symbol
611      */
612     public static Resource createSymbol(WriteGraph graph, Resource componentType) throws DatabaseException {
613         return NewSymbol.createSymbol(graph, componentType);
614     }
615
616     /**
617      * Converts to a <code>camelCase</code> name to a more user-readable
618      * <code>Camel Case</code> label.
619      * 
620      * <p>
621      * Examples
622      * <pre>
623      * "fooBarBazBAR" => "Foo Bar Baz BAR"
624      * " fooBarBazBAR" => " Foo Bar Baz BAR"
625      * "_fooBarBazBAR" => "_Foo Bar Baz BAR"
626      * "_FooBarBazBAR" => "_Foo Bar Baz BAR"
627      * " _ fooBarBazBAR" => " _ Foo Bar Baz BAR"
628      * </pre>
629      * 
630      * @param str camelCase SCL identifier name
631      * @return labelified Camel Case string
632      */
633     public static String camelCaseNameToLabel(String str) {
634         int len = str.length();
635         StringBuilder sb = new StringBuilder(len*2);
636
637         boolean wasLastUpper = false;
638         boolean isFirstEncounteredLetter = true;
639
640         for (int i = 0; i < len; ++i) {
641             char ch = str.charAt(i);
642
643             boolean space = Character.isWhitespace(ch);
644             if (space) {
645                 sb.append(ch);
646                 continue;
647             }
648
649             boolean isUpperCaseLetter = Character.isUpperCase(ch);
650             boolean isLetterOrDigit = Character.isLetterOrDigit(ch);
651             if (!isFirstEncounteredLetter && isUpperCaseLetter && !wasLastUpper && isLetterOrDigit) {
652                 sb.append(' ');
653                 sb.append(ch);
654             } else {
655                 if (isLetterOrDigit && isFirstEncounteredLetter)
656                     sb.append(Character.toUpperCase(ch));
657                 else
658                     sb.append(ch);
659                 if (isFirstEncounteredLetter)
660                     isFirstEncounteredLetter = !isLetterOrDigit;
661             }
662             wasLastUpper = isUpperCaseLetter;
663         }
664         return sb.toString();
665     }
666
667     public static void saveProceduralCodeWithUC(WriteGraph graph, Resource componentType, String newText) throws DatabaseException {
668         StructuralResource2 STR = StructuralResource2.getInstance(graph);
669         Resource code = graph.getPossibleObject(componentType, STR.ProceduralComponentType_code);
670         saveProceduralCode(graph, code, newText);
671     }
672     
673     public static void saveProceduralCode(WriteGraph graph, Resource resource, String newText) throws ServiceException {
674         graph.claimValue(resource, newText, Bindings.STRING);
675         Layer0Utils.addCommentMetadata(graph, "Saved Procedural Component Type SCL Code");
676     }
677 }