List of usage examples for com.google.gson JsonObject toString
@Override
public String toString()
From source file:com.controller.system.UserManager.java
/** * /* w w w.ja v a2 s. co m*/ * * @param session * @param req * @param rps * @param userHeader * @param depHeader * @return * @throws Exception */ @RequestMapping(params = "update", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public String doUpdate(HttpSession session, HttpServletRequest req, HttpServletResponse rps, @ModelAttribute UserHeader userHeader, @ModelAttribute DepHeader depHeader) throws Exception { int userID = ((UserHeader) session.getAttribute("LoginInfo")).getUserID(); //? Timestamp sysTime = new Timestamp(System.currentTimeMillis()); JsonObject jsonObj = new JsonObject(); try { //?Service UserHeaderService userHeaderService = (UserHeaderService) ServiceFactory .getService("userHeaderService"); UserHeader userObj = new UserHeader(); userObj.setAccount(userHeader.getAccount()); userObj = userHeaderService.findByOne(userObj); userObj.setUserName(userHeader.getUserName()); userObj.setEmail(userHeader.getEmail()); userObj.setUserLevel(userHeader.getUserLevel()); userObj.setDepHeader(depHeader); userObj.setModUserID(userID); userObj.setModTime(sysTime); if (userHeaderService.updateUserHeader(userObj)) { jsonObj.addProperty("success", "?"); } else { jsonObj.addProperty("fail", ""); } } catch (Exception e) { throw e; } return jsonObj.toString(); }
From source file:com.controller.system.UserManager.java
/** * //w ww . j a v a2s. c om * * @param req * @param rps * @param account * @return * @throws Exception */ @RequestMapping(params = { "del" }, method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public String doDel(HttpServletRequest req, HttpServletResponse rps, @RequestParam("account") String account) throws Exception { JsonObject jsonObj = new JsonObject(); try { //?Service UserHeaderService userHeaderService = (UserHeaderService) ServiceFactory .getService("userHeaderService"); UserHeader userObj = new UserHeader(); userObj.setAccount(account); userObj = userHeaderService.findByOne(userObj); if (userHeaderService.deleteUserHeader(userObj)) { jsonObj.addProperty("success", "?"); } else { jsonObj.addProperty("fail", ""); } } catch (Exception e) { throw e; } return jsonObj.toString(); }
From source file:com.couchbase.cbadmin.client.CouchbaseAdminImpl.java
License:Open Source License
/** * Add a view to the bucket. This is an extension API and is not strictly * administrative.//from w ww.ja va 2 s . c o m * * @param config The configuration object defining the view to be created * @param pollTimeout time to wait until the view becomes ready, in millis. * @throws RestApiException */ @Override public void defineView(ViewConfig config, long pollTimeout) throws RestApiException { JsonObject views = getViews(config.getBucketName(), config.getDesign()); // Format the URI StringBuilder ub = new StringBuilder().append('/').append("couchBase/").append(config.getBucketName()) .append("/_design/").append(config.getDesign()); HttpPut req = new HttpPut(); req.setHeader("Content-Type", "application/json"); try { JsonObject design = config.getDefinition(); design = mergeViews(views, design); req.setEntity(new StringEntity(design.toString())); } catch (UnsupportedEncodingException ex) { throw new RestApiException(ex); } try { getResponseJson(req, ub.toString(), 201); } catch (IOException ex) { throw new RestApiException(ex); } if (pollTimeout > 0) { Collection<String> vNames = config.getViewNames(); if (vNames == null || vNames.isEmpty()) { throw new IllegalArgumentException("No views defined"); } String vName = vNames.iterator().next(); long tmo = System.currentTimeMillis() + pollTimeout; String vUri = String.format("%s/_design/%s/_view/%s?limit=1", config.getBucketName(), config.getDesign(), vName); while (System.currentTimeMillis() < tmo) { try { getJson(vUri); return; } catch (IOException ex) { throw new RestApiException(ex); } catch (RestApiException ex) { if (ex.getStatusLine() == null) { throw ex; } int statusCode = ex.getStatusLine().getStatusCode(); if (statusCode != 500 && statusCode != 404) { throw ex; } logger.trace("While waiting for view", ex); // Squash } try { Thread.sleep(500); } catch (InterruptedException ex) { logger.error("While waiting.", ex); break; } } throw new RestApiException("Timed out waiting for view"); } }
From source file:com.createtank.payments.coinbase.CoinbaseApi.java
License:Apache License
private boolean doTokenRequest(Collection<BasicNameValuePair> params) throws IOException { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(OAUTH_BASE_URL + "/token"); List<BasicNameValuePair> paramBody = new ArrayList<BasicNameValuePair>(); paramBody.add(new BasicNameValuePair("client_id", clientId)); paramBody.add(new BasicNameValuePair("client_secret", clientSecret)); paramBody.addAll(params);/* w w w . j a v a 2 s. c om*/ post.setEntity(new UrlEncodedFormEntity(paramBody, "UTF-8")); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); if (code == 401) { return false; } else if (code != 200) { throw new IOException("Got HTTP response code " + code); } String responseString = EntityUtils.toString(response.getEntity()); JsonParser parser = new JsonParser(); JsonObject content = (JsonObject) parser.parse(responseString); System.out.print("content: " + content.toString()); accessToken = content.get("access_token").getAsString(); refreshToken = content.get("refresh_token").getAsString(); return true; }
From source file:com.createtank.payments.coinbase.CoinbaseApi.java
License:Apache License
private boolean doTokenRequest(Map<String, String> params) throws IOException { Map<String, String> paramsBody = new HashMap<String, String>(); paramsBody.put("client_id", clientId); paramsBody.put("client_secret", clientSecret); paramsBody.putAll(params);/*from ww w .j a va 2s . c om*/ String bodyStr = RequestClient.createRequestParams(paramsBody); System.out.println(bodyStr); HttpURLConnection conn = (HttpsURLConnection) new URL(OAUTH_BASE_URL + "/token").openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(bodyStr); writer.flush(); writer.close(); int code = conn.getResponseCode(); if (code == 401) { return false; } else if (code != 200) { throw new IOException("Got HTTP response code " + code); } String response = RequestClient.getResponseBody(conn.getInputStream()); JsonParser parser = new JsonParser(); JsonObject content = (JsonObject) parser.parse(response); System.out.print("content: " + content.toString()); accessToken = content.get("access_token").getAsString(); refreshToken = content.get("refresh_token").getAsString(); return true; }
From source file:com.createtank.payments.coinbase.CoinbaseApi.java
License:Apache License
/** * Generates a new bitcoin receive address for the user. * @return the newly generated bitcoind address * @throws IOException/*from ww w. ja va 2 s. c o m*/ */ public Address generateReceiveAddress() throws IOException { Map<String, String> params = new HashMap<String, String>(); if (apiKey != null) params.put("api_key", apiKey); JsonObject response = RequestClient.post(this, "account/generate_receive_address", params, accessToken); boolean success = response.get("success").getAsBoolean(); System.out.println(response.toString()); return success ? Address.fromJson(response) : null; }
From source file:com.createtank.payments.coinbase.RequestClient.java
License:Apache License
private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry, String accessToken) throws IOException, UnsupportedRequestVerbException { if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) { throw new UnsupportedRequestVerbException(); }//ww w.ja v a 2 s . c om if (api.allowSecure()) { HttpClient client = HttpClientBuilder.create().build(); String url = BASE_URL + method; HttpUriRequest request; switch (verb) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; default: throw new RuntimeException("RequestVerb not implemented: " + verb); } ((HttpEntityEnclosingRequestBase) request) .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON)); if (accessToken != null) request.addHeader("Authorization", String.format("Bearer %s", accessToken)); request.addHeader("Content-Type", "application/json"); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = EntityUtils.toString(response.getEntity()); if (responseString.startsWith("[")) { // Is an array responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(responseString); System.out.println(resp.toString()); return resp; } String url = BASE_URL + method; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(verb.name()); conn.addRequestProperty("Content-Type", "application/json"); if (accessToken != null) conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken)); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(json.toString()); writer.flush(); writer.close(); int code = conn.getResponseCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); return call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = getResponseBody(conn.getInputStream()); if (responseString.startsWith("[")) { responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); return (JsonObject) parser.parse(responseString); }
From source file:com.createtank.payments.coinbase.RequestClient.java
License:Apache License
private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params, boolean retry, String accessToken) throws IOException { if (api.allowSecure()) { HttpClient client = HttpClientBuilder.create().build(); String url = BASE_URL + method; HttpUriRequest request = null;// ww w. j ava 2 s . c om if (verb == RequestVerb.POST || verb == RequestVerb.PUT) { switch (verb) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; default: throw new RuntimeException("RequestVerb not implemented: " + verb); } List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>(); if (params != null) { List<BasicNameValuePair> convertedParams = convertParams(params); paramsBody.addAll(convertedParams); } ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8")); } else { if (params != null) { url = url + "?" + createRequestParams(params); } if (verb == RequestVerb.GET) { request = new HttpGet(url); } else if (verb == RequestVerb.DELETE) { request = new HttpDelete(url); } } if (request == null) return null; if (accessToken != null) request.addHeader("Authorization", String.format("Bearer %s", accessToken)); System.out.println("auth header: " + request.getFirstHeader("Authorization")); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); call(api, method, verb, params, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = EntityUtils.toString(response.getEntity()); if (responseString.startsWith("[")) { // Is an array responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(responseString); System.out.println(resp.toString()); return resp; } String paramStr = createRequestParams(params); String url = BASE_URL + method; if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE) url += "?" + paramStr; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(verb.name()); if (accessToken != null) conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken)); if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) { conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(paramStr); writer.flush(); writer.close(); } int code = conn.getResponseCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); return call(api, method, verb, params, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = getResponseBody(conn.getInputStream()); if (responseString.startsWith("[")) { responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); return (JsonObject) parser.parse(responseString); }
From source file:com.dardenestates.code.src.Servlets.JsonServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w. ja va 2s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); BufferedReader reader = request.getReader(); List<String> message = new ArrayList(); JsonObject jsonObject; if (reader.ready()) { JsonParser jsonParser = new JsonParser(); try { jsonObject = jsonParser.parse(reader).getAsJsonObject(); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.getStackTrace()); jsonObject = new JsonObject(); jsonObject.add("Exception_Code", new JsonPrimitive("malformed request structure")); } } else { jsonObject = new JsonObject(); jsonObject.add("Exception_Code", new JsonPrimitive("Empty Request")); System.out.println(" Empty Request "); } try (PrintWriter out = response.getWriter()) { out.write(jsonObject.toString()); } //extract the commandkey String commandKey = jsonObject.get("COMMANDKEY").getAsString(); // route the command RoutingEnum routingEnum = RoutingEnum.valueOf(commandKey); ControllerInterface command = routingEnum.getExecutable(); String urlLocation = routingEnum.getResponseURL(); if (command.validate(jsonObject, message, makeDataSource())) { MysqlDataSource dataSource = new MysqlDataSource(); if (command.processRequest(jsonObject, message, dataSource)) { response.sendRedirect(urlLocation); } } //get the value of command //match it with the enum }
From source file:com.denimgroup.threadfix.service.waf.RiverbedWebAppFirewallGenerator.java
License:Mozilla Public License
@Override protected String generateRuleWithParameter(String uri, String action, String id, String genericVulnName, String parameter) {/*from w w w. ja v a 2 s . c o m*/ JsonObject res = new JsonObject(); res.addProperty("match", "args"); res.addProperty("uri", uri); res.addProperty("action", action); res.addProperty("id", id); res.addProperty("genericVulnName", VULNERABILITY_CLASS_MAPPING.get(genericVulnName)); res.addProperty("parameter", parameter); return "\t" + res.toString() + ","; }