/** * Authenticate with the chosen bridge * * @param ip, the ip address of the bridge you want to authenticate with * @return the username of the hue bridge, that has been placed on the white list */ private String authWithBridge(String ip) throws URISyntaxException, MalformedURLException, UnsupportedEncodingException { URI uri = new URL("http://" + ip + "/api").toURI(); DefaultHttpClient client = new DefaultHttpClient(); HttpUriRequest request = new HttpPost(uri); JSONObject obj = new JSONObject(); try { obj.put("devicetype", "OpenRemoteController"); } catch (JSONException e) { logger.error("JSONExceptionn when creating json object", e); } StringEntity data = new StringEntity(obj.toString(), "UTF-8"); ((HttpPost) request).setEntity(data); String resp = ""; HttpResponse response = null; ResponseHandler<String> responseHandler = new BasicResponseHandler(); request.addHeader("User-Agent", "OpenRemoteController"); request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); request.addHeader("Content-Type", "applicaion/json"); try { response = client.execute(request); resp = responseHandler.handleResponse(response); } catch (ClientProtocolException e) { logger.error("ClientProtocolException when executing HTTP method", e); } catch (IOException e) { logger.error("IOException when executing HTTP method", e); } finally { try { if ((response != null) && (response.getEntity() != null)) { response.getEntity().consumeContent(); } } catch (IOException ignored) { } client.getConnectionManager().shutdown(); } JSONObject jsonResponse = null; String jsonUsername = ""; try { jsonResponse = new JSONArray(resp.toString()).getJSONObject(0).getJSONObject("success"); jsonUsername = jsonResponse.getString("username"); } catch (JSONException e) { logger.error("JSONException when reading returned json", e); } return jsonUsername; }
/** * Save the connected bridge to disk * * @param bridge, {@link Bridge} object that needs to be saved */ private void saveUsernameToDisk(Bridge bridge) throws JSONException { try { String content = bridge.bridgeToJson().toString(); File file = new File(BRIDGEFILE); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); System.out.println("Bridge saved to Disk"); } catch (IOException e) { logger.error("IOException when saving hue bridge info to disk", e); } }