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