summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/uic/barcode/asn1/uper/IntCoder.java
blob: 5964a645d58b50c947a8afb74360828fa789b034 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package org.uic.barcode.asn1.uper;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigInteger;

import org.uic.barcode.asn1.datatypes.Asn1BigInteger;
import org.uic.barcode.asn1.datatypes.Asn1Default;
import org.uic.barcode.asn1.datatypes.Asn1Integer;
import org.uic.barcode.asn1.datatypes.IntMinValue;
import org.uic.barcode.asn1.datatypes.IntRange;


class IntCoder implements Encoder, Decoder {



    @Override public <T> boolean canDecode(Class<T> classOfT, Annotation[] extraAnnotations) {
        return  classOfT  == Asn1Integer.class ||
        		classOfT  == Asn1BigInteger.class||
        		classOfT  == BigInteger.class ||
        		classOfT  == Long.class ||
        		classOfT  == Integer.class ||
        		classOfT  == Short.class ;
    }
    
    
    @Override public <T> T decode(BitBuffer bitbuffer,
            Class<T> classOfT, Field field,
            Annotation[] extraAnnotations)  {
        AnnotationStore annotations = new AnnotationStore(classOfT.getAnnotations(),extraAnnotations);
    	String pos = String.format("Position: %d.%d", bitbuffer.position()/8 , bitbuffer.position() % 8);
        UperEncoder.logger.debug(String.format("%s: INTEGER",pos));
        IntRange intRange = annotations.getAnnotation(IntRange.class);    
        IntMinValue minValue = annotations.getAnnotation(IntMinValue.class);     
        
        
        if (intRange == null) {
       		return decodeUnconstrainedInteger(bitbuffer, classOfT, extraAnnotations, minValue);
        }
        UperEncoder.logger.debug(String.format("Integer, range %d..%d", intRange.minValue(), intRange.maxValue()));
       	return decodeConstrainedInteger(bitbuffer, classOfT, intRange, extraAnnotations);
    }

    @SuppressWarnings("unchecked")
	private <T> T decodeConstrainedInteger(BitBuffer bitbuffer, Class<T> classOfT, IntRange intRange,	Annotation[] extraAnnotations) {

     long   value = UperEncoder.decodeConstrainedInt(bitbuffer, intRange);
     UperEncoder.logger.debug(String.format("decoded as %d", value));
     
     try {
    	 if (classOfT == Asn1BigInteger.class) {
    		 return ((T) new Asn1BigInteger(value));
    	 } else if (classOfT == Asn1Integer.class) {
    		 return (T) new Asn1Integer(value);         		 
    	 } else if (classOfT == BigInteger.class) {
    		 return (T) BigInteger.valueOf(value);           		
    	 } else if (classOfT == Long.class) {
    		 return (T) Long.valueOf(value);        			
    	 } else if (classOfT == Integer.class) {
    		 return (T) Integer.valueOf(Long.valueOf(value).intValue());    
    	 } else if (classOfT == Short.class) {
    		 return (T) Short.valueOf(Long.valueOf(value).shortValue());       
    	 } 
     } catch (Exception e) {
    	 throw new IllegalArgumentException("size too small " + classOfT.getName() + ": " + e);
     }
     
	 return null;
    	 

	}

	@Override public <T> boolean canEncode(T obj, Annotation[] extraAnnotations) {
        return  obj instanceof Asn1Integer ||
        		obj instanceof Asn1BigInteger ||
        		obj instanceof BigInteger ||
                obj instanceof Long ||
                obj instanceof Integer ||
                obj instanceof Short;
    }

    @Override public <T> void encode(BitBuffer bitbuffer, T obj, Annotation[] extraAnnotations) throws Asn1EncodingException {
        Class<?> type = obj.getClass();
        AnnotationStore annotations = new AnnotationStore(type.getAnnotations(), extraAnnotations);
        IntRange range = annotations.getAnnotation(IntRange.class);
        IntMinValue minValue = annotations.getAnnotation(IntMinValue.class); 
        int position = bitbuffer.position();
        
        //get value       
        if (range == null) {
        	
        	try {
        		encodeUnconstrainedInteger(bitbuffer, obj, extraAnnotations,minValue);
        	} catch (Asn1EncodingException e) {
            throw new Asn1EncodingException(" " + type.getSimpleName(), e);
        	} catch (Exception e1){
        		throw new Asn1EncodingException(" " + type.getSimpleName() + " - " + e1.getLocalizedMessage());
        	}
        	UperEncoder.logger.debug(String.format("INT(%s): %s", obj, bitbuffer.toBooleanStringFromPosition(position)));

        	
        } else {

        	try {
        		
        		long value = 0;
        		if (obj instanceof BigInteger) {
        			try {
        				value = ((BigInteger) obj).longValue();    
        			} catch (Exception e) {
        				
        				UperEncoder.logger.debug("constrained BigInteger is too big for constrained int");
        				throw new Asn1EncodingException("constrained BigInteger is too big for constrained int" + type.getSimpleName());
        			}
        		} if (obj instanceof Asn1BigInteger) {
        			try {
        				value = ((Asn1BigInteger) obj).longValue();    
        			} catch (Exception e) {
        				
        				UperEncoder.logger.debug("constrained Asn1BigInteger is too big for constrained int");
        				throw new Asn1EncodingException("constrained Asn1BigInteger is too big for constrained int" + type.getSimpleName());
        			}
        		} if (obj instanceof Asn1Integer) {
        			try {
        				value = Asn1Integer.toLong((Asn1Integer) obj);    
        			} catch (Exception e) {
        				
        				UperEncoder.logger.debug("constrained BigInteger is too big for constrained int");
        				throw new Asn1EncodingException("constrained BigInteger is too big for constrained int" + type.getSimpleName());
        			}
        		} else if (obj instanceof Long) {
        			value = ((Long) obj).longValue();        			
        		} else if (obj instanceof Integer) {
        			value = ((Integer) obj).longValue();       
        		} else if (obj instanceof Short) {
        			value = ((Short) obj).longValue();       
        		}         		

        		UperEncoder.encodeConstrainedInt(bitbuffer, value, range.minValue(), range.maxValue(), range.hasExtensionMarker());
        	} catch (Asn1EncodingException e) {
        		throw new Asn1EncodingException(" " + type.getSimpleName(), e);
        	} catch (Exception e1){
        		throw new Asn1EncodingException(" " + type.getSimpleName() + " - " + e1.getLocalizedMessage());
        	}
        	UperEncoder.logger.debug(String.format("INT(%s): %s", obj, bitbuffer.toBooleanStringFromPosition(position)));
        }
        return;
    }
    
    private <T> void encodeUnconstrainedInteger(BitBuffer bitbuffer, Object obj, Annotation[] annotations, IntMinValue minValue) throws Asn1EncodingException {

    	   	
        BigInteger bint = null;
    	try {
    		if (obj instanceof BigInteger) {
    			bint = (BigInteger) obj;
    		} else if (obj instanceof Asn1BigInteger) {
    			bint = BigInteger.valueOf(((Asn1BigInteger) obj).longValue());
    		} else if (obj instanceof Asn1Integer) {
    			bint = BigInteger.valueOf(((Asn1Integer) obj).value());
    		} else if (obj instanceof Long) {
    			bint = BigInteger.valueOf(((Long) obj).longValue());    			
    		} else if (obj instanceof Integer) {
    			bint = BigInteger.valueOf(((Integer) obj).longValue());       
    		} else if (obj instanceof Short) {
    			bint = BigInteger.valueOf(((Short) obj).longValue());       
    		} 	
    	} catch (Exception e1){
    		throw new Asn1EncodingException(" " + obj.getClass().getSimpleName() + " - " + e1.getLocalizedMessage());
    	}
    	
        
    	if (minValue != null) {
    		bint.subtract(BigInteger.valueOf(minValue.minValue()));
    	}

        byte[] array = bint.toByteArray();
        int lengthInOctets = array.length;
        int position1 = bitbuffer.position();
        try {
            UperEncoder.encodeLengthDeterminant(bitbuffer, lengthInOctets);
        } catch (Asn1EncodingException e) {
            throw new Asn1EncodingException(" length determinant of INTEGER", e);
        }
        int position2 = bitbuffer.position();
        for (byte b : array) {
            bitbuffer.putByte(b);
        }
        UperEncoder.logger.debug(String.format("INTEGER Int(%s): len %s, val %s", bint.toString(),
                 bitbuffer.toBooleanString(position1, position2 - position1),
                 bitbuffer.toBooleanStringFromPosition(position2)));
        return;
    }
    
    @SuppressWarnings("unchecked")
	public <T> T decodeUnconstrainedInteger(BitBuffer bitbuffer,  Class<T> classOfT,  Annotation[] extraAnnotations,IntMinValue minValue)  {
        AnnotationStore annotations = new AnnotationStore(classOfT.getAnnotations(), extraAnnotations);
    	
    	String pos = String.format("%d.%d", bitbuffer.position()/8 , bitbuffer.position() % 8);
        UperEncoder.logger.debug(String.format("Position %s BIG INT",pos));
        IntRange intRange = annotations.getAnnotation(IntRange.class);
        if (intRange != null && intRange.maxValue() > 0) { 
        	throw new UnsupportedOperationException("Big int with upper range is not supported yet"); 
        }

        int lengthInOctets = (int) UperEncoder.decodeLengthDeterminant(bitbuffer);
        BitBuffer valueBits = ByteBitBuffer.allocate(lengthInOctets * 8);
        for (int i = 0; i < lengthInOctets * 8; i++) {
            valueBits.put(bitbuffer.get());
        }
        valueBits.flip();
        BigInteger resultValue = new BigInteger(+1, valueBits.array());
        if (minValue != null) {
        	resultValue.add(BigInteger.valueOf(minValue.minValue()));
        }
        
        UperEncoder.logger.debug(String.format("INTEGER Decoded as %s", resultValue));
 
        try {
        	if (classOfT == Asn1BigInteger.class) {
        		return (T) new Asn1BigInteger(resultValue);
        	} else if (classOfT == BigInteger.class) {
        		return (T) resultValue;           		
        	} else if (classOfT == Long.class) {
        		return (T) bigToLong(resultValue);        			
        	} else if (classOfT == Integer.class) {
        		return (T) bigToInteger(resultValue);   
        	} else if (classOfT == Short.class) {
        		return (T) bigToShort(resultValue);         
        	} 	
        } catch (Exception e){
        	UperEncoder.logger.debug(String.format("INTEGER Decoded as %s is too big for data type", resultValue));
        }
		return null;
    }

    private Long bigToLong(BigInteger b) {
    	
    	Long l = b.longValue();
    	
    	if (BigInteger.valueOf(l).equals(b)) {
    		return l;
    	} else {
    		throw new ArithmeticException("BigInteger To Long failed");
    	}

    }
    
    private Integer bigToInteger(BigInteger b) {
    	
    	Integer l = b.intValue();
    	
    	if (BigInteger.valueOf(l).equals(b)) {
    		return l;
    	} else {
    		throw new ArithmeticException("BigInteger To Integer failed");
    	}

    }
    
    private Short bigToShort(BigInteger b) {
    	
    	Short l = b.shortValue();
    	
    	if (BigInteger.valueOf(l).equals(b)) {
    		return l;
    	} else {
    		throw new ArithmeticException("BigInteger To Short failed");
    	}

    }
    
	@SuppressWarnings("unchecked")
	@Override
	public <T> T getDefault(Class<T> classOfT, Annotation[] extraAnnotations) {
		AnnotationStore annotations = new AnnotationStore(classOfT.getAnnotations(), extraAnnotations);
        Asn1Default defaultAnnotation = annotations.getAnnotation(Asn1Default.class);
        if (defaultAnnotation == null) return null;
        //check whether the class has a constructor for numeric types
        String valueString = defaultAnnotation.value();
        long value = Long.parseLong(valueString);
        
        try {
       	 if (classOfT == Asn1BigInteger.class) {
       		 return ((T) new Asn1BigInteger(value));
       	 } else if (classOfT == BigInteger.class) {
       		 return (T) BigInteger.valueOf(value);           		
       	 } else if (classOfT == Long.class) {
       		 return (T) Long.valueOf(value);        			
       	 } else if (classOfT == Integer.class) {
       		 return (T) Integer.valueOf(Long.valueOf(value).intValue());    
       	 } else if (classOfT == Short.class) {
       		 return (T) Short.valueOf(Long.valueOf(value).shortValue());       
       	 } 
        } catch (Exception e) {
       	 throw new IllegalArgumentException("size too small " + classOfT.getName() + ": " + e);
        }        
        
        return null;
	}

}