1 /*******************************************************************************
2 * Copyright (c) 2007, 2011 Association for Decentralized Information Management in
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.databoard.util;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.ObjectInputStream;
18 import java.io.ObjectOutputStream;
19 import java.io.OutputStream;
20 import java.util.Random;
22 import org.simantics.databoard.Bindings;
23 import org.simantics.databoard.Files;
24 import org.simantics.databoard.adapter.AdaptException;
25 import org.simantics.databoard.adapter.RuntimeAdaptException;
26 import org.simantics.databoard.binding.Binding;
27 import org.simantics.databoard.binding.OptionalBinding;
28 import org.simantics.databoard.binding.RecordBinding;
29 import org.simantics.databoard.binding.error.BindingException;
30 import org.simantics.databoard.binding.error.RuntimeBindingException;
31 import org.simantics.databoard.binding.util.RandomValue;
32 import org.simantics.databoard.parser.repository.DataTypeSyntaxError;
33 import org.simantics.databoard.parser.repository.DataValueRepository;
34 import org.simantics.databoard.serialization.Serializer;
35 import org.simantics.databoard.serialization.SerializerConstructionException;
36 import org.simantics.databoard.type.Component;
37 import org.simantics.databoard.type.Datatype;
40 * Record classes enable databoard features by sub-classing Bean.
42 * Instructions, the fields must be public, or have public get/setters.
43 * Sub-class gains the following services:
45 * toString #toString()
46 * string #print() / #parse()
47 * Hash-Equals #hashCode() / #equals()
48 * Comparable #compareTo()
49 * Serialization #serialize()/#deserialize(), #readObject()/#writeObject(), #readFile()/#writeFile()
50 * Cloning #clone() / #readFrom()
51 * Initialization #init() / #setToDefault() / #setToRandom()
53 * The class must be compatible with databoard's type system.
55 * See BeanExample for example.
57 * The identify of this class is composed from all the fields. The identity
58 * affects to the behavior how hash and equals are counted.
60 * If only some fields compose the hash-equals-compareTo identity, use {@link Bean.Id} instead.
61 * In this case the identifying fields have @Identity annotation.
65 * public class MyClass extends Bean.Id {
66 * public @Identify String id;
70 * @author toni.kalajainen
72 public class Bean implements Cloneable, /*Serializable, */Comparable<Bean> {
74 transient protected RecordBinding binding;
77 this.binding = Bindings.getBindingUnchecked( getClass() );
80 protected Bean(Binding binding) {
81 this.binding = (RecordBinding) binding;
85 * Return datatype binding to this class.
87 * @return record binding
89 public RecordBinding getBinding() {
94 * Read all field values from another object. All fields are deep-cloned,
95 * except immutable values which are referenced.
99 public void readFrom(Bean other) {
100 binding.readFromUnchecked(other.binding, other, this);
103 public void readAvailableFields(Bean other) {
104 if ( other.binding instanceof RecordBinding == false ) return;
105 Component components[] = binding.type().getComponents();
106 for (int i=0; i<components.length; i++) {
107 Component c = components[i];
108 int ix = other.binding.getComponentIndex(c.name);
109 if ( ix<0 ) continue;
111 Object value = other.binding.getComponent(other, ix);
112 Object value2 = Bindings.adapt(value, other.binding.getComponentBinding(ix), binding.getComponentBinding(i));
113 binding.setComponent(this, i, value2);
114 } catch (AdaptException e) {
115 throw new RuntimeException(e);
116 } catch (BindingException e) {
117 throw new RuntimeBindingException(e);
123 * Set default value to any null field that is not optional.
127 // Set value to uninitialized fields
128 for (int i=0; i<binding.getComponentCount(); i++) {
129 Object v = binding.getComponent(this, i);
130 Binding cb = binding.componentBindings[i];
131 if (v==null && cb instanceof OptionalBinding==false) {
132 v = cb.createDefault();
133 binding.setComponent(this, i, v);
136 } catch (BindingException e) {
137 throw new RuntimeBindingException(e);
142 * Sets all fields to default values.
143 * Strings are set to "", arrays cleared or set to minimum count,
144 * numbers are set to 0.
146 public void setToDefault() {
147 for (int i=0; i<binding.componentBindings.length; i++)
149 Binding cb = binding.componentBindings[i];
151 binding.setComponent(this, i, cb.createDefault());
152 } catch (BindingException e) {
158 * Sets all fields with random values
160 public void setToRandom(Random random) {
161 RandomValue rv = new RandomValue( random );
162 for (int i=0; i<binding.componentBindings.length; i++)
164 Binding cb = binding.componentBindings[i];
166 binding.setComponent(this, i, cb.createRandom( rv ));
167 } catch (BindingException e) {
173 public int hashCode() {
175 return binding.hashValue( this );
176 } catch (BindingException e) {
182 public Bean clone() {
184 return (Bean) binding.clone(this);
185 } catch (AdaptException e) {
186 throw new RuntimeAdaptException(e);
191 * Compare to another bean of same datatype. (Can be different binding)
194 public boolean equals(Object obj) {
195 if (obj==null) return false;
196 if (obj==this) return true;
197 if ( obj instanceof Bean == false ) return false;
198 Bean other = (Bean) obj;
199 if (other.binding==binding) {
200 return binding.equals(this, obj);
203 return Bindings.equals(binding, this, other.binding, other);
204 } catch (BindingException e) {
205 throw new RuntimeBindingException(e);
210 public boolean equalContents(Object obj) {
211 if (obj==null) return false;
212 if (obj==this) return true;
213 Bean other = (Bean) obj;
214 if (other.binding==binding) {
215 return binding.equals(this, obj);
218 return Bindings.equals(binding, this, other.binding, other);
219 } catch (BindingException e) {
220 throw new RuntimeBindingException(e);
226 public int compareTo(Bean o) {
227 if (o==null) return -1;
228 return binding.compare(this, o);
232 * Print the object as string
236 public String toString() {
238 return binding.toString(this);
239 } catch (BindingException e) {
240 return e.getMessage();
245 * Print the value in string format
248 * @throws IOException
250 public void print(Appendable out) throws IOException {
252 DataValueRepository rep = new DataValueRepository();
253 binding.printValue(this, out, rep, false);
254 } catch (BindingException e) {
255 throw new RuntimeBindingException(e);
260 * Print the value to Databoard string format
262 * @return Bean in Databoard string format
263 * @throws IOException
265 public String print() throws IOException {
267 StringBuilder sb = new StringBuilder();
268 DataValueRepository rep = new DataValueRepository();
269 binding.printValue(this, sb, rep, false);
270 return sb.toString();
272 /* StringBuilder sb = new StringBuilder();
273 DataValueRepository rep = new DataValueRepository();
274 rep.setTypeRepository( Datatypes.datatypeRepository );
275 DataValuePrinter vp = new DataValuePrinter(sb, rep);
276 vp.setFormat( PrintFormat.MULTI_LINE );
277 DataTypePrinter tp = new DataTypePrinter( sb );
278 tp.setLinedeed( true );
279 rep.put("value", binding, this);
281 for (String name : rep.getValueNames()) {
282 MutableVariant value = rep.get(name);
283 Datatype type = value.type();
288 for (String name : rep.getValueNames()) {
289 MutableVariant value = rep.get(name);
290 Datatype type = value.type();
291 sb.append( name+" : " );
297 System.out.println(sb);
298 return sb.toString();
300 } catch (BindingException e) {
301 throw new RuntimeBindingException(e);
306 * Print the value to Databoard string format
308 * @return string representation in a line
309 * @throws IOException
311 public String printLine() throws IOException {
313 StringBuilder sb = new StringBuilder();
314 DataValueRepository rep = new DataValueRepository();
315 binding.printValue(this, sb, rep, true);
316 return sb.toString();
317 } catch (BindingException e) {
318 throw new RuntimeBindingException(e);
323 * Read the contents from Databoard String
325 * @throws DataTypeSyntaxError
327 public void parse( String str ) throws DataTypeSyntaxError {
329 DataValueRepository rep = new DataValueRepository();
330 Object v = binding.parseValue( str, rep );
332 binding.readFrom(binding, v, this);
333 } catch (BindingException e) {
334 throw new RuntimeBindingException( e );
338 public void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException {
340 Serializer s = Bindings.getSerializer(binding);
341 s.deserialize((InputStream)in, this);
342 } catch (SerializerConstructionException e) {
343 throw new IOException(e);
347 public void writeObject(ObjectOutputStream out) throws IOException {
349 Serializer s = Bindings.getSerializer(binding);
350 s.serialize((OutputStream) out, this);
351 } catch (SerializerConstructionException e) {
352 throw new IOException(e);
357 * Serialize the object to a byte array
359 * @return bean as serialized
360 * @throws IOException
362 public byte[] serialize() throws IOException {
364 Serializer s = Bindings.getSerializer(binding);
365 return s.serialize( this );
366 } catch (SerializerConstructionException e) {
367 throw new IOException(e);
372 * Deserialize the object from a byte array
375 * @throws IOException
377 public void deserialize( byte[] data ) throws IOException {
379 Serializer s = Bindings.getSerializer(binding);
381 s.deserialize(data, this);
382 } catch (SerializerConstructionException e) {
383 throw new IOException(e);
387 public void readFile( File file ) throws IOException {
389 Files.readFile(file, binding, this);
392 public void writeFile( File file ) throws IOException {
393 Files.writeFile(file, binding, this);
396 public void assertIsValid() throws BindingException {
397 binding.assertInstaceIsValid(this);
400 public void setField(String fieldName, Binding fieldBinding, Object field) throws BindingException {
402 int index = binding.getComponentIndex(fieldName);
403 if ( index<0 ) throw new BindingException("There is no field "+fieldName);
404 Binding localFieldBinding = binding.getComponentBinding(index);
405 if ( localFieldBinding instanceof OptionalBinding ) {
406 OptionalBinding ob = (OptionalBinding) localFieldBinding;
407 if ( field == null ) {
408 binding.setComponent(this, index, ob.createNoValue());
410 Object newValue = Bindings.adapt(field, fieldBinding, ob.componentBinding);
411 binding.setComponent(this, index, ob.createValue(newValue));
414 Object newValue = Bindings.adapt(field, fieldBinding, localFieldBinding);
415 binding.setComponent(this, index, newValue);
417 } catch (AdaptException e) {
418 if ( e.getCause() !=null && e.getCause() instanceof BindingException ) throw (BindingException) e.getCause();
419 throw new BindingException(e);
423 public void setField(int fieldIndex, Binding fieldBinding, Object field) throws BindingException {
425 if ( fieldIndex<0 ) throw new BindingException("There is no field #"+fieldIndex);
426 Binding localFieldBinding = binding.getComponentBinding(fieldIndex);
427 if ( localFieldBinding instanceof OptionalBinding ) {
428 OptionalBinding ob = (OptionalBinding) localFieldBinding;
429 if ( field == null ) {
430 binding.setComponent(this, fieldIndex, ob.createNoValue());
432 Object newValue = Bindings.adapt(field, fieldBinding, ob.componentBinding);
433 binding.setComponent(this, fieldIndex, ob.createValue(newValue));
436 Object newValue = Bindings.adapt(field, fieldBinding, localFieldBinding);
437 binding.setComponent(this, fieldIndex, newValue);
439 } catch (AdaptException e) {
440 if ( e.getCause() !=null && e.getCause() instanceof BindingException ) throw (BindingException) e.getCause();
441 throw new BindingException(e);
445 public boolean hasField(String fieldName) throws BindingException {
446 return binding.getComponentIndex(fieldName)>=0;
450 * Get binding of a field
453 * @return binding or null of field does not exist
454 * @throws BindingException
456 public Binding getFieldBinding(String fieldName) throws BindingException {
457 int index = binding.getComponentIndex(fieldName);
458 if ( index<0 ) return null;
459 Binding r = binding.getComponentBinding(index);
460 if ( r!=null && r instanceof OptionalBinding ) {
461 r = ((OptionalBinding)r).componentBinding;
467 * Get value of a field
469 * @return value or null if field does not exist
470 * @throws BindingException
472 public Object getField(String fieldName) throws BindingException {
473 int index = binding.type().getComponentIndex2(fieldName);
474 if (index<0) return null;
475 return binding.getComponent(this, index);
479 * Get value of a field
481 * @return value or null if field does not exist
482 * @throws BindingException
484 public Object getField(int fieldIndex) throws BindingException {
485 return binding.getComponent(this, fieldIndex);
489 * Get value of a field
491 * @param binding requested binding
492 * @return value or null if field does not exist
493 * @throws BindingException
495 public Object getField(String fieldName, Binding binding) throws BindingException {
496 int index = this.binding.type().getComponentIndex2(fieldName);
497 if (index<0) return null;
498 Object obj = this.binding.getComponent(this, index);
499 if ( obj == null ) return null;
500 Binding fieldBinding = this.binding.getComponentBinding(index);
501 if ( fieldBinding instanceof OptionalBinding ) {
502 fieldBinding = ((OptionalBinding)fieldBinding).componentBinding;
505 return Bindings.adapt(obj, fieldBinding, binding);
506 } catch (AdaptException e) {
507 if ( e.getCause() !=null && e.getCause() instanceof BindingException ) throw (BindingException) e.getCause();
508 throw new BindingException(e);
513 * Get value of a field
515 * @return value or null if field does not exist
516 * @throws RuntimeBindingException
518 public Object getFieldUnchecked(String fieldName) throws RuntimeBindingException {
519 int index = binding.type().getComponentIndex2(fieldName);
520 if (index<0) return null;
522 return binding.getComponent(this, index);
523 } catch (BindingException e) {
524 throw new RuntimeBindingException(e);
529 * Get value of a field
531 * @return value or null if field does not exist
532 * @throws RuntimeBindingException
534 public Object getFieldUnchecked(int fieldIndex) throws RuntimeBindingException {
536 return binding.getComponent(this, fieldIndex);
537 } catch (BindingException e) {
538 throw new RuntimeBindingException(e);
543 * Get identifier binding. Use @Identifier annotation to indicate which
544 * fields compose the identifier of the record.
546 * @return idenfitier binding.
547 * @throws BindingException there is no identifier
549 public Binding getIdentifierBinding() throws BindingException {
550 Datatype idType = binding.type().getIdentifierType();
551 if (idType == null) throw new BindingException("There is are no @Identifier fields in the bean");
552 return Bindings.getBinding( idType );
556 * Get identifier of the object. Use @Identifier annotation to indicate which
557 * fields compose the identifier of the record.
560 * @throws BindingException
562 public Object getIdentifier() throws BindingException
564 int ids[] = binding.type().getIdentifiers();
565 if (ids.length == 0) throw new BindingException("There is are no @Identifier fields in the bean");
566 if (ids.length == 1) return binding.getComponent(this, ids[0]);
567 RecordBinding rb = (RecordBinding) getIdentifierBinding();
568 Object result = rb.createPartial();
571 rb.setComponent(result, ix++, binding.getComponent(this, i));
577 * In this version of the bean, the hash/equals compares to identifiers.
578 * Identifier is a field with @Idenfitier annotation.
580 public static class Id extends Bean {
582 protected Id(Binding binding) {
587 public int hashCode() {
590 for (int index : binding.type().getIdentifiers())
592 Object c = binding.getComponent(this, index);
593 Binding cb = binding.getComponentBinding(index);
594 hash = 13*hash + cb.hashValue(c);
596 } catch (BindingException e) {
602 * Compare to another bean of same datatype for equal identifier. (Can be different binding)
605 public boolean equals(Object obj) {
606 if (obj==null) return false;
607 if (obj==this) return true;
608 if ( obj instanceof Bean == false ) return false;
609 Bean other = (Bean) obj;
611 if (other.binding==binding) {
613 for (int index : binding.type().getIdentifiers())
615 Object tc = binding.getComponent(this, index);
616 Object oc = binding.getComponent(other, index);
617 Binding cb = binding.getComponentBinding(index);
618 if ( !cb.equals(tc, oc) ) return false;
623 for (int index : binding.type().getIdentifiers())
625 Object tc = binding.getComponent(this, index);
626 Object oc = binding.getComponent(other, index);
627 Binding tcb = binding.getComponentBinding(index);
628 Binding ocb = other.binding.getComponentBinding(index);
629 if ( !Bindings.equals(tcb, tc, ocb, oc) ) return false;
633 } catch (BindingException e) {
634 throw new RuntimeBindingException(e);