/** * Executes a query. * * @param command Name of the command to execute * @param parameters Parameters * @param manager Reference back to business layer * @return Parsed JSON object, empty object on error. */ public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) { URLConnection uc = null; try { final ObjectMapper mapper = Client.MAPPER; if (mUrlSuffix == null) { throw new NoSettingsException(); } final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP); uc = url.openConnection(); uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT); uc.setReadTimeout(mSocketReadTimeout); if (authEncoded != null) { uc.setRequestProperty("Authorization", "Basic " + authEncoded); } uc.setRequestProperty("Content-Type", "application/json"); uc.setDoOutput(true); final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1"); if (parameters != null) { data.put("params", parameters); } final JsonFactory jsonFactory = new JsonFactory(); final JsonGenerator jg = jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8); jg.setCodec(mapper); // POST data jg.writeTree(data); jg.flush(); final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream()); jp.setCodec(mapper); final JsonNode ret = jp.readValueAs(JsonNode.class); return ret; } catch (MalformedURLException e) { manager.onError(e); } catch (IOException e) { int responseCode = -1; try { responseCode = ((HttpURLConnection) uc).getResponseCode(); } catch (IOException e1) { } // do nothing, getResponse code failed so treat as default i/o exception. if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED))); } else { manager.onError(e); } } catch (NoSettingsException e) { manager.onError(e); } return new ObjectNode(null); }
public void write(JsonGenerator jg, T value) throws IOException { if (jg.getCodec() == null) { jg.setCodec(new ObjectMapper()); } jg.writeObject(value); }