Casts a value to the specified type. @param value value to be cast @param type type (can be null) @return cast value @throws QueryException query exception
(final Object value, final String type)
| 706 | * @throws QueryException query exception |
| 707 | */ |
| 708 | private Value cast(final Object value, final String type) throws QueryException { |
| 709 | Object object = value; |
| 710 | if(object instanceof final String string) { |
| 711 | final StringList strings = new StringList(1); |
| 712 | // strings containing multiple items (value \1 ...) |
| 713 | if(string.indexOf('\1') == -1) { |
| 714 | strings.add(string); |
| 715 | } else { |
| 716 | object = strings.add(string.split("\1")).toArray(); |
| 717 | } |
| 718 | |
| 719 | // subtypes overriding the global value (value \2 type) |
| 720 | if(string.indexOf('\2') != -1) { |
| 721 | final ValueBuilder vb = new ValueBuilder(this, strings.size()); |
| 722 | for(final String str : strings) { |
| 723 | final int i = str.indexOf('\2'); |
| 724 | final String val = i == -1 ? str : str.substring(0, i); |
| 725 | final String tp = i == -1 ? type : str.substring(i + 1); |
| 726 | vb.add(cast(val, tp)); |
| 727 | } |
| 728 | return vb.value(); |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | // no type specified: return original value or convert as Java object |
| 733 | if(type == null || type.isEmpty()) { |
| 734 | return object instanceof final Value val ? val : JavaCall.toValue(object, this, null); |
| 735 | } |
| 736 | |
| 737 | // convert JSON input |
| 738 | if(type.equalsIgnoreCase(MainParser.JSON.name())) { |
| 739 | final JsonParserOptions jp = new JsonParserOptions(); |
| 740 | jp.set(JsonOptions.FORMAT, JsonFormat.W3); |
| 741 | try { |
| 742 | final TextInput ti = new TextInput(new IOContent(object.toString())); |
| 743 | return JsonConverter.get(jp).convert(ti, "", null, this); |
| 744 | } catch(final IOException ex) { |
| 745 | throw new QueryException(ex); |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | // parse target type |
| 750 | final StaticContext sc = main != null ? main.sc : new StaticContext(this); |
| 751 | final SeqType st = new QueryParser(type, null, this, sc).parseSeqType(); |
| 752 | if(st.eq(Types.EMPTY_SEQUENCE_Z)) return Empty.VALUE; |
| 753 | final Type tp = st.type; |
| 754 | |
| 755 | // cast XQuery values |
| 756 | if(object instanceof final Value val) { |
| 757 | // cast single item |
| 758 | if(val.size() == 1) return tp.cast((Item) val, this, null); |
| 759 | // cast sequence |
| 760 | final ValueBuilder vb = new ValueBuilder(this, val.size()); |
| 761 | for(final Item item : val) vb.add(tp.cast(item, this, null)); |
| 762 | return vb.value(tp); |
| 763 | } |
| 764 | |
| 765 | // cast sequences |