@GET @Path("{route_id}") @Produces(MediaType.APPLICATION_JSON) public String getPlace(@PathParam("route_id") String routeID) { JSONObject reply = new JSONObject(); try { syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); Entity result = (Entity) syncCache.get(routeID); if (result != null) return reply .append("status", "OK") .append("message", "Found in memcache.") .append("Route Object", result) .toString(); return reply.append("status", "fail").append("message", "Not found in memcache.").toString(); } catch (Exception e) { return new JSONObject() .append("status", "fail") .append("message", "Route object with ID " + routeID + " not found.") .toString(); } }
private JSONObject getRestaurantsById(String businessId) { try { Statement stmt = conn.createStatement(); String sql = "SELECT business_id, name, full_address, categories, stars, latitude, longitude, city, state, image_url from " + "RESTAURANTS where business_id='" + businessId + "'" + " ORDER BY stars DESC"; ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { JSONObject obj = new JSONObject(); obj.append("business_id", rs.getString("business_id")); obj.append("name", rs.getString("name")); obj.append("stars", rs.getFloat("stars")); obj.append("latitude", rs.getFloat("latitude")); obj.append("longitude", rs.getFloat("longitude")); obj.append("full_address", rs.getString("full_address")); obj.append("city", rs.getString("city")); obj.append("state", rs.getString("state")); obj.append("categories", DBImport.stringToJSONArray(rs.getString("categories"))); obj.append("image_url", rs.getString("image_url")); return obj; } } catch (Exception e) { /* report an error */ System.out.println(e.getMessage()); } return null; }
public JSONArray GetRestaurantsNearLoation(double lat, double lon) { try { if (conn == null) { return null; } Statement stmt = conn.createStatement(); String sql = "SELECT business_id, name, full_address, categories, stars, latitude, longitude, city, state from RESTAURANTS LIMIT 10"; // execute query expect result set ResultSet rs = stmt.executeQuery(sql); List<JSONObject> list = new ArrayList<JSONObject>(); while (rs.next()) { JSONObject obj = new JSONObject(); obj.append("business_id", rs.getString("business_id")); obj.append("name", rs.getString("name")); obj.append("stars", rs.getFloat("stars")); obj.append("latitude", rs.getFloat("latitude")); obj.append("longitude", rs.getFloat("longitude")); obj.append("full_address", rs.getString("full_address")); obj.append("city", rs.getString("city")); obj.append("state", rs.getString("state")); obj.append("categories", DBImport.stringToJSONArray(rs.getString("categories"))); list.add(obj); } return new JSONArray(list); } catch (Exception e) { /* report an error */ System.out.println(e.getMessage()); } return null; }
public static void createRoom(String userId, String roomName, String roomPassword) { try { JSONObject jsonObj = new JSONObject(); jsonObj.append("cmd", "CREATE_ROOM"); jsonObj.append("scene", "LOBBY"); JSONObject jsonObjNest = new JSONObject(); jsonObjNest.append("roomName", roomName); jsonObjNest.append("roomPwd", roomPassword); jsonObj.append("parameters", jsonObjNest); PlayersController.sendSessionMsgToDarkstar(getPlayerClient(userId), jsonObj.toString()); } catch (Exception e) { e.printStackTrace(); } }
@Path("/{id_user}/{id_command}") @POST public Response postReturn( @PathParam("id_user") Integer idUser, @PathParam("id_command") Integer idCommand, @QueryParam("id_personalisation") List<Integer> idsPersonalisation) { // TODO update rendre id_Personalisation facultatif pour pouvoir // renvoyer TOUTE la commande d'un coups ? Command currentCommand = Database.getCommand(idCommand); if (!idUser.equals(currentCommand.getUserId())) { JSONObject resultError = new JSONObject(); resultError.append("error", "This is not your command"); return Response.status(Status.FORBIDDEN).entity(resultError.toString(2)).build(); } // TODO test si moins de 30 jours Command newCommand = new Command(Database.getNextCommandId(), idUser); for (Integer idPerso : idsPersonalisation) { Personalisation curPerso = currentCommand.getPersonalisation(idPerso); if (curPerso.equals(null)) { JSONObject resultError = new JSONObject(); resultError.append("error", "This personalisation is not in this command"); resultError.append("id_personalisation", idPerso); return Response.status(Status.FORBIDDEN).entity(resultError.toString(2)).build(); } newCommand.add(curPerso); } newCommand.setStatus("paid"); Database.addCommand(newCommand); Return newReturn = new Return(Database.getNextReturnId(), idCommand, newCommand.getId(), idsPersonalisation); Database.addReturn(newReturn); JSONObject result = new JSONObject(); result.append("id_new_Command", newCommand.getId()); return Response.ok().entity(result.toString(2)).build(); }
public Serializable getCacheableObject(String feedUri) throws Exception { JSONObject json = new JSONObject(); PreparedQuery pq = datastoreService.prepare(new Query("feeds")); for (Entity entity : pq.asIterable()) { JSONObject item = new JSONObject(); item.put("uri", "/addama/feeds/" + entity.getKey().getName()); item.put("creator", entity.getProperty("creator").toString()); json.append("items", item); } return json.toString(); }
public void getAllMessage() throws JSONException { List<Message> messageList = messageService.getMessageList((Long) session.get("id")); JSONObject result = new JSONObject(); for (Message message : messageList) { JSONObject mjson = new JSONObject(); mjson.accumulate("invitor_name", message.getInviter().getName()); mjson.accumulate("invitor_email", message.getInviter().getEmail()); mjson.accumulate("content", message.getContent()); mjson.accumulate("create_date", message.getDateCreated()); result.append("messageList", mjson); } sendMsg(result.toString()); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.addHeader("Access-Control-Allow-Origin", "*"); String username = ""; if (request.getParameter("username") != null) { username = request.getParameter("username"); } JSONObject obj = new JSONObject(); try { obj.append("username", username); obj.append("name", "panda express"); obj.append("location", "downtown"); obj.append("country", "united states"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter out = response.getWriter(); out.print(obj); out.flush(); out.close(); }
@DELETE @Path("{route_id}") @Produces(MediaType.APPLICATION_JSON) public String deletePlace(@PathParam("route_id") String routeID) { syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); JSONObject reply = new JSONObject(); try { syncCache.delete(routeID); return reply .append("status", "OK") .append("message", "successfully deleted route " + routeID + " from " + "memcache") .toString(); } catch (Exception e) { return new JSONObject().append("status", "fail").append("message", e.getMessage()).toString(); } }
@Override protected ServerStatus _doIt() { try { /* get available orgs */ URI targetURI = URIUtil.toURI(target.getUrl()); URI orgsURI = targetURI.resolve("/v2/organizations"); GetMethod getDomainsMethod = new GetMethod(orgsURI.toString()); HttpUtil.configureHttpMethod(getDomainsMethod, target); getDomainsMethod.setQueryString("inline-relations-depth=1"); // $NON-NLS-1$ ServerStatus status = HttpUtil.executeMethod(getDomainsMethod); if (!status.isOK()) return status; /* extract available orgs */ JSONObject orgs = status.getJsonData(); if (orgs.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) { return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null); } /* look if the domain is available */ JSONObject result = new JSONObject(); int resources = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).length(); for (int k = 0; k < resources; ++k) { JSONObject orgJSON = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).getJSONObject(k); List<Space> spaces = new ArrayList<Space>(); status = getSpaces(spaces, orgJSON); if (!status.isOK()) return status; OrgWithSpaces orgWithSpaces = new OrgWithSpaces(); orgWithSpaces.setCFJSON(orgJSON); orgWithSpaces.setSpaces(spaces); result.append("Orgs", orgWithSpaces.toJSON()); } return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } catch (Exception e) { String msg = NLS.bind("An error occured when performing operation {0}", commandName); // $NON-NLS-1$ logger.error(msg, e); return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e); } }
public JSONObject toJSONObject() throws JSONException { JSONObject jo = new JSONObject(); jo.put("classname", this.getClass().getName()); jo.put("policyName", policyName); jo.put("ruleCombiner", ruleCombiner); jo.put("target", target.toJSONObject()); Set<String> keys = definedVars.keySet(); JSONObject dv = new JSONObject(); for (String k : keys) { dv.put(k, definedVars.get(k).toJSONObject()); } jo.put("definedVars", dv); for (XACML3PolicyRule r : rules) { jo.append("rules", r.toJSONObject()); } return jo; }
private JSONObject addInclude(JSONObject json, String include) throws JSONException { return json.append("includes", include); }
public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // look for a passed in theme context (content generator, other named area) String moduleName = req.getParameter("context"); OutputStream out = resp.getOutputStream(); resp.setContentType("text/javascript"); // $NON-NLS-1$ resp.setHeader("Cache-Control", "no-cache"); // $NON-NLS-1$ IUserSettingService settingsService = PentahoSystem.get(IUserSettingService.class, getPentahoSession(req)); String activeTheme = (String) getPentahoSession(req).getAttribute("pentaho-user-theme"); String ua = req.getHeader("User-Agent"); // check if we're coming from a mobile device, if so, lock to system default (crystal) if (!StringUtils.isEmpty(ua) && ua.matches(".*(?i)(iPad|iPod|iPhone|Android).*")) { activeTheme = PentahoSystem.getSystemSetting("default-theme", "crystal"); } if (activeTheme == null) { try { activeTheme = settingsService.getUserSetting("pentaho-user-theme", null).getSettingValue(); } catch ( Exception ignored) { // the user settings service is not valid in the agile-bi deployment of // the server } if (activeTheme == null) { activeTheme = PentahoSystem.getSystemSetting("default-theme", "crystal"); } } out.write( ("\n\n// Theming scripts. This file is generated by (" + getClass().getName() + ") and cannot be found on disk\n") .getBytes()); out.write(("var active_theme = \"" + activeTheme + "\";\n\n").getBytes()); // Build-up JSON graph for system theme. JSONObject root = new JSONObject(); JSONObject themeObject; for (String systemThemeName : themeManager.getSystemThemeIds()) { Theme theme = themeManager.getSystemTheme(systemThemeName); themeObject = new JSONObject(); root.put(theme.getId(), themeObject); themeObject.put("rootDir", theme.getThemeRootDir()); for (ThemeResource res : theme.getResources()) { themeObject.append("resources", res.getLocation()); } } out.write(("var core_theme_tree = " + root.toString() + ";\n\n").getBytes()); out.write( "// Inject the theme script to handle the insertion of requested theme resources\n\n" .getBytes()); ModuleThemeInfo moduleThemeinfo = themeManager.getModuleThemeInfo(moduleName); if (moduleThemeinfo != null) { // Build-up JSON graph for module theme. root = new JSONObject(); for (Theme theme : moduleThemeinfo.getModuleThemes()) { themeObject = new JSONObject(); root.put(theme.getName(), themeObject); themeObject.put("rootDir", theme.getThemeRootDir()); for (ThemeResource res : theme.getResources()) { themeObject.append("resources", res.getLocation()); } } out.write(("var module_theme_tree = " + root.toString() + ";\n\n").getBytes()); } // createElement & insertBefore out.write( ("(function() {\n" + "var script = document.createElement('script');\n" + "script.type = 'text/javascript';\n" + // "script.async = false;\n" + "script.src = CONTEXT_PATH + 'js/themeResources.js';\n" + "var existing = document.getElementsByTagName('script')[0];\n" + "existing.parentNode.insertBefore(script, existing);\n" + "}());") .getBytes()); } catch (IOException e) { logger.debug("IO exception creating Theme info", e); throw new ServletException(e); } catch (JSONException e) { logger.debug("JSON exception creating Theme info", e); throw new ServletException(e); } }