View Javadoc
1   /*
2   Copyright (c) 2016 James Ahlborn
3   
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7   
8       http://www.apache.org/licenses/LICENSE-2.0
9   
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15  */
16  
17  package com.healthmarketscience.jackcess.impl.expr;
18  
19  import java.math.BigDecimal;
20  import java.time.LocalDateTime;
21  
22  import com.healthmarketscience.jackcess.expr.EvalException;
23  import com.healthmarketscience.jackcess.expr.LocaleContext;
24  import com.healthmarketscience.jackcess.expr.Value;
25  
26  /**
27   *
28   * @author James Ahlborn
29   */
30  public abstract class BaseValue implements Value
31  {
32    @Override
33    public boolean isNull() {
34      return(getType() == Type.NULL);
35    }
36  
37    @Override
38    public boolean getAsBoolean(LocaleContext ctx) {
39      throw invalidConversion(Type.LONG);
40    }
41  
42    @Override
43    public String getAsString(LocaleContext ctx) {
44      throw invalidConversion(Type.STRING);
45    }
46  
47    @Override
48    public LocalDateTime getAsLocalDateTime(LocaleContext ctx) {
49      return (LocalDateTime)getAsDateTimeValue(ctx).get();
50    }
51  
52    @Override
53    public Value getAsDateTimeValue(LocaleContext ctx) {
54      throw invalidConversion(Type.DATE_TIME);
55    }
56  
57    @Override
58    public Integer getAsLongInt(LocaleContext ctx) {
59      throw invalidConversion(Type.LONG);
60    }
61  
62    @Override
63    public Double getAsDouble(LocaleContext ctx) {
64      throw invalidConversion(Type.DOUBLE);
65    }
66  
67    @Override
68    public BigDecimal getAsBigDecimal(LocaleContext ctx) {
69      throw invalidConversion(Type.BIG_DEC);
70    }
71  
72    protected EvalException invalidConversion(Type newType) {
73      return new EvalException(
74          this + " cannot be converted to " + newType);
75    }
76  
77    protected Integer roundToLongInt(LocaleContext ctx) {
78      return getAsBigDecimal(ctx).setScale(0, NumberFormatter.ROUND_MODE)
79        .intValueExact();
80    }
81  
82    @Override
83    public String toString() {
84      return "Value[" + getType() + "] '" + get() + "'";
85    }
86  }