UrlHelper { public JSONObject parseJsonObjectFromUrl(String url) { try { Proxy proxy; String httpProxyHost = configurationHelper.getProperty(ConfigurationValue.HTTP_PROXY_HOST); Integer httpProxyPort = configurationHelper.getProperty(ConfigurationValue.HTTP_PROXY_PORT, Integer.class); if (StringUtils.isNotBlank(httpProxyHost) && httpProxyPort != null) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)); } else { proxy = Proxy.NO_PROXY; } InputStream inputStream = urlOperations.openStream(new URL(url), proxy); try { JSONParser jsonParser = new JSONParser(); return (JSONObject) jsonParser.parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); } catch (ParseException e) { throw new IllegalArgumentException(String.format("Failed to parse JSON object from the URL: url=\"%s\"", url), e); } finally { inputStream.close(); } } catch (IOException e) { throw new IllegalArgumentException(String.format("Failed to read JSON from the URL: url=\"%s\"", url), e); } }  JSONObject parseJsonObjectFromUrl(String url);  }
@Test public void testParseJsonObjectFromUrl() { assertEquals(MockUrlOperationsImpl.MOCK_JSON_STRING, urlHelper.parseJsonObjectFromUrl(MockUrlOperationsImpl.MOCK_URL_VALID).toJSONString()); }
@Test public void testParseJsonObjectFromUrlJsonParseException() { try { urlHelper.parseJsonObjectFromUrl(MockUrlOperationsImpl.MOCK_URL_JSON_PARSE_EXCEPTION); } catch (IllegalArgumentException e) { assertEquals(String.format("Failed to parse JSON object from the URL: url=\"%s\"", MockUrlOperationsImpl.MOCK_URL_JSON_PARSE_EXCEPTION), e.getMessage()); } }
@Test public void testParseJsonObjectFromUrlMalformedURLException() { try { urlHelper.parseJsonObjectFromUrl(MockUrlOperationsImpl.MOCK_URL_MALFORMED_URL_EXCEPTION); } catch (IllegalArgumentException e) { assertEquals(String.format("Failed to read JSON from the URL: url=\"%s\"", MockUrlOperationsImpl.MOCK_URL_MALFORMED_URL_EXCEPTION), e.getMessage()); } }
@Test public void testParseJsonObjectFromUrlWithProxySettings() throws Exception { Map<String, Object> overrideMap = new HashMap<>(); overrideMap.put(ConfigurationValue.HTTP_PROXY_HOST.getKey(), HTTP_PROXY_HOST); overrideMap.put(ConfigurationValue.HTTP_PROXY_PORT.getKey(), HTTP_PROXY_PORT); modifyPropertySourceInEnvironment(overrideMap); try { assertEquals(MockUrlOperationsImpl.MOCK_JSON_STRING, urlHelper.parseJsonObjectFromUrl(MockUrlOperationsImpl.MOCK_URL_VALID).toJSONString()); } finally { restorePropertySourceInEnvironment(); } }
@Test public void testParseJsonObjectFromUrlWithProxySettingsNoProxyPort() throws Exception { Map<String, Object> overrideMap = new HashMap<>(); overrideMap.put(ConfigurationValue.HTTP_PROXY_HOST.getKey(), HTTP_PROXY_HOST); modifyPropertySourceInEnvironment(overrideMap); try { assertEquals(MockUrlOperationsImpl.MOCK_JSON_STRING, urlHelper.parseJsonObjectFromUrl(MockUrlOperationsImpl.MOCK_URL_VALID).toJSONString()); } finally { restorePropertySourceInEnvironment(); } }