3
3
import com .fasterxml .jackson .core .JsonProcessingException ;
4
4
import com .fasterxml .jackson .databind .DeserializationFeature ;
5
5
import com .fasterxml .jackson .databind .ObjectMapper ;
6
- import com .sun .net .httpserver .HttpHandler ;
7
6
8
7
import java .io .IOException ;
9
8
import java .net .MalformedURLException ;
12
11
13
12
public class BarcodeReader {
14
13
15
- private final static String TAG = HttpHandler .class .getSimpleName ();
14
+ private final static String TAG = BarcodeReader .class .getSimpleName ();
16
15
private final static Logger logger =
17
16
Logger .getLogger (Logger .GLOBAL_LOGGER_NAME );
18
- private final static String barcodeURI = "https://jsonmock.hackerrank.com/api/inventory?barcode= " ;
17
+ private final static String inventoryURI = "https://jsonmock.hackerrank.com/api/inventory" ;
19
18
20
- public Inventory read (int barcode )
21
- throws BarcodeNotFoundException {
22
- Inventory [] inventories = null ;
19
+ public Inventory read (int barcode ) {
20
+ Inventory inventory = null ;
21
+ String barcodeURI = inventoryURI + "?barcode=" ;
23
22
24
23
try {
25
24
String inventoryJSONString = InputStreamConverter .toString (
26
- HttpRequests .get (barcodeURI +barcode ))
27
- .toString ();
25
+ HttpRequests .get (barcodeURI +barcode ));
28
26
29
- inventories = getInventories (inventoryJSONString );
27
+ inventory = getInventories (inventoryJSONString )[ 0 ] ;
30
28
29
+ } catch (InventoryNotFoundException e ) {
30
+ if (logger .isLoggable (Level .INFO )) {
31
+ logger .log (Level .INFO , TAG + " InventoryNotFoundException: " + e .getMessage ());
32
+ }
31
33
} catch (MalformedURLException e ) {
32
34
if (logger .isLoggable (Level .SEVERE )) {
33
35
logger .log (Level .SEVERE , TAG + " MalformedURLException: " + e .getMessage ());
@@ -37,19 +39,15 @@ public Inventory read(int barcode)
37
39
logger .severe (TAG + " IOException: " + e .getMessage ());
38
40
}
39
41
} catch (Exception e ) {
40
- if (logger .isLoggable (Level .SEVERE )) {
41
- logger .severe (TAG + " Exception: " + e .getMessage ());
42
+ if (logger .isLoggable (Level .INFO )) {
43
+ logger .info (TAG + " Exception: " + e .getMessage ());
42
44
}
43
45
}
44
46
45
- if ( inventories .length == 0 ) {
46
- throw new BarcodeNotFoundException ("Barcode Not Found!" );
47
- }
48
-
49
- return inventories [0 ];
47
+ return inventory ;
50
48
}
51
49
52
- private Inventory [] getInventories (String inventories )
50
+ private Inventory [] getInventories (String jsonInventories )
53
51
throws JsonProcessingException {
54
52
55
53
ObjectMapper objectMapper = new ObjectMapper ();
@@ -58,7 +56,7 @@ private Inventory[] getInventories(String inventories)
58
56
objectMapper .configure (DeserializationFeature .USE_JAVA_ARRAY_FOR_JSON_ARRAY , true );
59
57
60
58
return objectMapper
61
- .readValue (inventories ,
59
+ .readValue (jsonInventories ,
62
60
Inventory [].class );
63
61
}
64
62
0 commit comments