@Test public void jsonToStingTest() throws Exception { File jsonFile = new File("C:/Users/NB/Documents/harlo/nNlmKXiQDBSyTdngEQKORlRVAJ.json"); BufferedReader reader = new BufferedReader(new FileReader(jsonFile)); StringBuilder jsonString = new StringBuilder(); String line = reader.readLine(); while (line != null) { jsonString.append(line); line = reader.readLine(); } JsonParser parser = new JsonParser(); JsonObject j3mJSON = (JsonObject) parser.parse(jsonString.toString()); String jsonResult = j3mJSON.toString(); for (int i = 0; i < 100; i++) { Assert.assertEquals(" i is " + i, jsonResult, j3mJSON.toString()); } for (int i = 0; i < 100; i++) { j3mJSON = new JsonObject(); JsonObject j3mJSON2 = (JsonObject) parser.parse(jsonString.toString()); j3mJSON.add("new", j3mJSON2); jsonResult = "{\"new\":" + j3mJSON2.toString() + "}"; for (int j = 0; j < 100; j++) { Assert.assertEquals(" i is " + i + " j is " + j, jsonResult, j3mJSON.toString()); } } }
@GET @Path("{from}/{destination}/{date}/{numtickets}") @Produces("application/json") public Response getAirlinesByOriginDestinationDateNumberOfTickets( @PathParam("from") String from, @PathParam("destination") String destination, @PathParam("date") String date, @PathParam("numtickets") int numtickets) throws ParseException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date2 = formatter.parse(date); JsonArray jsonFlights = new JsonArray(); JsonObject jsonAirline = new JsonObject(); List<FlightInstance> Flightlist = f.getFlightsByOriginDestinationDateNumberOfTickets(from, destination, date2, numtickets); try { FlightInstance fi = Flightlist.get(0); jsonAirline.addProperty("airline", fi.getFlight().getAirline().getName()); for (FlightInstance fl : Flightlist) { jsonFlights.add(flightToJson(fl)); } jsonAirline.add("flights", jsonFlights); return Response.status(Response.Status.OK).entity(jsonAirline.toString()).build(); } catch (Exception e) { return Response.status(Response.Status.OK).entity(jsonAirline.toString()).build(); } }
public void showPrevWinner(Reservation obj) { TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); String m_deviceId = TelephonyMgr.getDeviceId(); JsonObject bidPrevData = new JsonObject(); // ValueProvider obj1 = new ValueProvider(); JsonObject bidPrevDataBody = new JsonObject(); bidPrevData.addProperty("user_id", "user4"); bidPrevData.addProperty("room_no", obj.getLocation()); bidPrevData.addProperty("start_time", String.valueOf(obj.getStartDate().getTime())); bidPrevData.addProperty("end_time", String.valueOf(obj.getEndDate().getTime())); bidPrevData.addProperty("temperature_f", "0"); // bidData.addProperty("temperature_f", temp_1.getValue(); bidPrevData.addProperty("bid_amount", "0"); bidPrevData.addProperty("timestamp", date.getTime()); bidPrevDataBody.add("bidTemperature", bidPrevData); JsonObject creditData = new JsonObject(); JsonObject creditDataBody = new JsonObject(); creditData.addProperty("user_id", "user4"); creditDataBody.add("UserCredit", creditData); // Gets winning temperature before with bidding is done new GetWinnerHistory(this).execute(bidPrevDataBody.toString()); // // // Gets user credit before the bid is done. new GetCreditController(this).execute(creditDataBody.toString()); // currentWinner.setText(obj1.getPrevWinner()); // // myCoins.setText(obj1.getCredit()); }
/** * Publish data to the IBM Internet of Things Foundation.<br> * This method allows QoS to be passed as an argument * * @param event Name of the dataset under which to publish the data * @param data Object to be added to the payload as the dataset * @param qos Quality of Service - should be 0, 1 or 2 * @return Whether the send was successful. */ public boolean publishEvent(String event, Object data, int qos) { if (!isConnected()) { return false; } final String METHOD = "publishEvent(2)"; JsonObject payload = new JsonObject(); String timestamp = ISO8601_DATE_FORMAT.format(new Date()); payload.addProperty("ts", timestamp); JsonElement dataElement = gson.toJsonTree(data); payload.add("d", dataElement); String topic = "iot-2/evt/" + event + "/fmt/json"; LoggerUtility.fine(CLASS_NAME, METHOD, "Topic = " + topic); LoggerUtility.fine(CLASS_NAME, METHOD, "Payload = " + payload.toString()); MqttMessage msg = new MqttMessage(payload.toString().getBytes(Charset.forName("UTF-8"))); msg.setQos(qos); msg.setRetained(false); try { mqttAsyncClient.publish(topic, msg).waitForCompletion(); } catch (MqttPersistenceException e) { e.printStackTrace(); return false; } catch (MqttException e) { e.printStackTrace(); return false; } return true; }
public void saveScriptOnEms( VNFCInstance vnfcInstance, Object scripts, VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception { log.debug("Scripts are: " + scripts.getClass().getName()); if (scripts instanceof String) { String scriptLink = (String) scripts; log.debug("Scripts are: " + scriptLink); JsonObject jsonMessage = getJsonObject("CLONE_SCRIPTS", scriptLink, this.scriptPath); executeActionOnEMS( vnfcInstance.getHostname(), jsonMessage.toString(), virtualNetworkFunctionRecord, vnfcInstance); } else if (scripts instanceof Set) { Iterable<Script> scriptSet = (Set<Script>) scripts; for (Script script : scriptSet) { log.debug("Sending script encoded base64 "); String base64String = Base64.encodeBase64String(script.getPayload()); log.trace("The base64 string is: " + base64String); JsonObject jsonMessage = getJsonObjectForScript("SAVE_SCRIPTS", base64String, script.getName(), this.scriptPath); executeActionOnEMS( vnfcInstance.getHostname(), jsonMessage.toString(), virtualNetworkFunctionRecord, vnfcInstance); } } }
/** * Send data. * * @param obj the obj */ public void sendData(Reservation obj) { JsonObject bidData = new JsonObject(); JsonObject bidDataBody = new JsonObject(); TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); String m_deviceId = TelephonyMgr.getDeviceId(); bidData.addProperty("user_id", "user4"); bidData.addProperty("room_no", obj.getLocation()); bidData.addProperty("start_time", String.valueOf(obj.getStartDate().getTime())); bidData.addProperty("end_time", String.valueOf(obj.getEndDate().getTime())); bidData.addProperty("temperature_f", temp_1.getText().toString()); // bidData.addProperty("temperature_f", temp_1.getValue(); bidData.addProperty("bid_amount", coins_1.getText().toString()); bidData.addProperty("timestamp", date.getTime()); bidDataBody.add("bidTemperature", bidData); // GetBidResult winTemp = new GetBidResult(); // Log.d("test_2", winTemp.doInBackground()); // currentWinner.setText(winTemp.doInBackground()); Log.d("test_2", bidDataBody.toString()); new BidTemperatureController(this).execute(bidDataBody.toString()); // Adding credits data // Log.d("test_2", creditDataBody.toString()); }
public <T> T json2Object(Class<T> cls) { System.out.println("data str = " + data.toString()); if (null == data) { return null; } T t = GsonTools.getObject(data.toString(), cls); return t; }
@Override public InputStream getInputStream() throws IOException { if (inputStream == null) { outClosed = true; JsonArray users = new JsonParser() .parse(new String(outputStream.toByteArray(), Charsets.UTF_8)) .getAsJsonArray(); StringBuilder reply = new StringBuilder("["); StringBuilder missingUsers = new StringBuilder("["); for (JsonElement user : users) { String username = user.getAsString().toLowerCase(); String info = cache.getIfPresent(username); if (info != null) { reply.append(info).append(","); } else { missingUsers.append("\"").append(username).append("\"").append(","); } } if (missingUsers.length() > 1) { missingUsers.deleteCharAt(missingUsers.length() - 1).append("]"); } if (missingUsers.length() > 2) { HttpURLConnection connection; if (proxy == null) { connection = (HttpURLConnection) cachedStreamHandler.getDefaultConnection(url); } else { connection = (HttpURLConnection) cachedStreamHandler.getDefaultConnection(url, proxy); } connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoInput(true); connection.setDoOutput(true); OutputStream out = connection.getOutputStream(); out.write(missingUsers.toString().getBytes(Charsets.UTF_8)); out.flush(); out.close(); JsonArray newUsers = new JsonParser() .parse(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8)) .getAsJsonArray(); for (JsonElement user : newUsers) { JsonObject u = user.getAsJsonObject(); cache.put(u.get("name").getAsString(), u.toString()); reply.append(u.toString()).append(","); } responseCode = connection.getResponseCode(); errorStream = connection.getErrorStream(); } else { responseCode = HTTP_OK; } if (reply.length() > 1) { reply.deleteCharAt(reply.length() - 1); } inputStream = new ByteArrayInputStream(reply.append("]").toString().getBytes(Charsets.UTF_8)); } return inputStream; }
/** 取消订单接口 */ private void cancelOrder() { showDialog(); JsonObject jsonParam = new JsonObject(); jsonParam.addProperty("orderNoList", group.get(groupPosition).getOrderNoGroup()); Ioc.getIoc().getLogger().i("取消预订接口参数:" + jsonParam.toString()); InternetConfig config = new InternetConfig(); config.setKey(27); FastHttpHander.ajaxString( Url.HOTELRESERVE_ACCURATE_CLEARRESERVE, jsonParam.toString(), config, this); }
public void appendRootModuleInfo( Appendable appendable, boolean isDebugMode, Function<String, String> moduleNameToUri) throws IOException { ModuleConfig moduleConfig = config.getModuleConfig(); JsonObject plovrModuleInfo = createModuleInfo(moduleConfig); appendable.append("PLOVR_MODULE_INFO=").append(plovrModuleInfo.toString()).append(";\n"); JsonObject plovrModuleUris = createModuleUris(moduleConfig, moduleNameToUri); appendable.append("PLOVR_MODULE_URIS=").append(plovrModuleUris.toString()).append(";\n"); appendable.append("PLOVR_MODULE_USE_DEBUG_MODE=" + isDebugMode + ";\n"); }
@Path("/writeAttribute/{ObjID}/{ObjInsId}/{resourceId}") @PUT @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public Response sendWriteAttribute( @PathParam("ObjID") String objectId, @PathParam("ObjInsId") String objectInstanceId, @PathParam("resourceId") String resourceID, @QueryParam("ep") String endPoint, @QueryParam("pmin") String pmin, @QueryParam("pmax") String pmax, @QueryParam("gt") String gt, @QueryParam("lt") String lt, @QueryParam("st") String st) throws InterruptedException { String string = objectId + "/" + objectInstanceId + "/" + resourceID; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("operation", "writeAttribute"); jsonObject.addProperty("directory", string); JsonObject value = new JsonObject(); if (pmin != null) { value.addProperty("pmin", pmin); } if (pmax != null) { value.addProperty("pmax", pmax); } if (gt != null) { value.addProperty("gt", gt); } if (lt != null) { value.addProperty("lt", lt); } if (st != null) { value.addProperty("st", st); } jsonObject.addProperty("value", value.toString()); // String directory = // "{\"operation\":\"discover\""+","+"\""+"directory\":"+"\""+objectId+"/"+objectInstanceId+"/"+resourceID+"\"}"; Info.setInfo(endPoint, jsonObject.toString()); CountDownLatch signal = Info.getCountDown(endPoint); if (signal == null) { return Response.status(200).entity("Devices not registered yet").build(); } signal.countDown(); CountDownLatch signalRead = new CountDownLatch(1); Info.setCountDownLatchMessageMap(endPoint, signalRead); signalRead.await(); return Response.status(200).entity("writeAttribute success").build(); }
@Override protected void channelRead0( ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception { String jsonReturn = ""; String chapterId = getParameter("chapter"); List<String> chaptersIds = getQueryStringIds(); if (isGet(fullHttpRequest) && chapterId == null && chaptersIds != null && chaptersIds.size() == 0) { List<SubCategoryData> chapters = getStorage().getSubCategories(getDomain().getWebappName(), "chapters"); JsonArray chaptersArray = new JsonArray(); for (SubCategoryData chapter : chapters) { chaptersArray.add(CourseAssembler.buildPageJsonFromSubCategoryData(chapter)); } JsonObject topLevelObject = new JsonObject(); topLevelObject.add("chapters", chaptersArray); jsonReturn = topLevelObject.toString(); } else if (isGet(fullHttpRequest) && chapterId != null) { SubCategoryData chapter = getStorage().getSubCategory(getDomain().getWebappName(), "chapters", chapterId); if (chapter != null) { JsonObject topLevelObject = new JsonObject(); JsonObject chapterObject = CourseAssembler.buildPageJsonFromSubCategoryData(chapter); topLevelObject.add("chapter", chapterObject); jsonReturn = topLevelObject.toString(); } } else if (isGet(fullHttpRequest) && chaptersIds != null && chaptersIds.size() > 0) { JsonArray chaptersArray = new JsonArray(); for (String id : chaptersIds) { SubCategoryData chapter = getStorage().getSubCategory(getDomain().getWebappName(), "chapters", id); if (chapter != null) { JsonObject chapterObject = CourseAssembler.buildPageJsonFromSubCategoryData(chapter); chaptersArray.add(chapterObject); } } JsonObject topLevelObject = new JsonObject(); topLevelObject.add("chapters", chaptersArray); jsonReturn = topLevelObject.toString(); } writeContentsToBuffer(channelHandlerContext, jsonReturn, "application/json"); }
/** * Adds access point with the given name * * @param mac the mac address given in the request * @return a JSON response */ @RequestMapping(value = "/accesspoints/add", method = RequestMethod.GET) public @ResponseBody String addAccessPoint(@RequestParam String mac) { JsonObject json = new JsonObject(); AccessPoint newAP = new AccessPoint(); newAP.setMacAddr(mac); try { apService.createAccessPoint(newAP); } catch (AccessPointAlreadyExistsException e) { json.addProperty("success", Boolean.FALSE); json.addProperty("exception", "Access point already exists : " + e.getMacAddr()); return json.toString(); } json.addProperty("success", Boolean.TRUE); return json.toString(); }
private void publish(JsonObject jsonPubMsg) throws MqttException, UnsupportedEncodingException { final String METHOD = "publish1"; String topic = jsonPubMsg.get("topic").getAsString(); int qos = jsonPubMsg.get("qos").getAsInt(); JsonObject payload = jsonPubMsg.getAsJsonObject("payload"); LoggerUtility.log( Level.FINE, CLASS_NAME, METHOD, ": Topic(" + topic + ") qos=" + qos + " payload (" + payload.toString() + ")"); MqttMessage message = new MqttMessage(); message.setPayload(payload.toString().getBytes("UTF-8")); message.setQos(qos); publish(DeviceTopic.get(topic), message); }
@Test public void lackOfParams_messageAndNotificaiton() { JsonObject payload = new JsonObject(); payload.add("platform", Platform.all().toJSON()); payload.add("audience", Audience.all().toJSON()); System.out.println("json string: " + payload.toString()); try { _client.sendPush(payload.toString()); } catch (APIConnectionException e) { e.printStackTrace(); } catch (APIRequestException e) { assertEquals(LACK_OF_PARAMS, e.getErrorCode()); } }
/** * Create a configuration file based on the internally stored configuration. * * @return The StringBuffer object associated with the internal JSON configuration file. */ private static StringBuffer create() { Logger.log("Creating default configuration file 'config.json'...", Logger.CRITICAL); StringBuffer fileData = getLocalConfig(); try { JsonObject json = (JsonObject) new JsonParser().parse(fileData.toString()); // # Remove config version from the output // # This config string will be used internally for // # tracking versions of cingif files when writing new ones // # or receiving new ones. json.remove("config-version"); // # Write configuration file. FileOutputStream out = new FileOutputStream("config.json"); out.write(json.toString().getBytes()); out.close(); } catch (JsonParseException e) { // # Should never get here because the config file is packaged internaly... // # If it fails, probably a developer not formatting the config file properly. Logger.log( "Compiling and creating the config file failed. Ensure you have properly formatted JSON data before recompiling your extension.", Logger.CRITICAL); } catch (IOException e) { Logger.log("Failed to write the configuration file: " + e.getMessage(), Logger.CRITICAL); } return fileData; }
@Override public JsonElement serialize(Crowd crowd, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); if (crowd.getId() == null || crowd.getId().isEmpty()) { object.addProperty("_id", "-1"); } else { object.addProperty("_id", crowd.getId()); } object.addProperty("name", crowd.getName()); object.addProperty("owner", crowd.getOwner()); if (crowd.getMembers() == null || crowd.getMembers().isEmpty()) { object.add("members", JsonNull.INSTANCE); } else { JsonArray members = new JsonArray(); for (MemberId memberId : crowd.getMembers()) { members.add(new JsonPrimitive(memberId.getId())); object.add("members", members); } } Log.i("CrowdSerializer", "Serialized: " + object.toString()); return object; }
/** * Creates a User based on a Microsoft Azure Mobile Service JSON object containing a UserId and * Authentication Token * * @param json JSON object used to create the User * @return The created user if it is a valid JSON object. Null otherwise * @throws MobileServiceException */ private MobileServiceUser createUserFromJSON(JsonObject json) throws MobileServiceException { if (json == null) { throw new IllegalArgumentException("json can not be null"); } // If the JSON object is valid, create a MobileServiceUser object if (json.has(USER_JSON_PROPERTY)) { JsonObject jsonUser = json.getAsJsonObject(USER_JSON_PROPERTY); if (!jsonUser.has(USERID_JSON_PROPERTY)) { throw new JsonParseException(USERID_JSON_PROPERTY + " property expected"); } String userId = jsonUser.get(USERID_JSON_PROPERTY).getAsString(); MobileServiceUser user = new MobileServiceUser(userId); if (!json.has(TOKEN_JSON_PARAMETER)) { throw new JsonParseException(TOKEN_JSON_PARAMETER + " property expected"); } user.setAuthenticationToken(json.get(TOKEN_JSON_PARAMETER).getAsString()); return user; } else { // If the JSON contains an error property show it, otherwise raise // an error with JSON content if (json.has("error")) { throw new MobileServiceException(json.get("error").getAsString()); } else { throw new JsonParseException(json.toString()); } } }
public static String a(Map var0) { JsonObject var1 = new JsonObject(); Iterator var2 = var0.entrySet().iterator(); while (var2.hasNext()) { Entry var3 = (Entry) var2.next(); if (((class_nf) var3.getValue()).b() != null) { JsonObject var4 = new JsonObject(); var4.addProperty("value", Integer.valueOf(((class_nf) var3.getValue()).a())); try { var4.add("progress", ((class_nf) var3.getValue()).b().a()); } catch (Throwable var6) { b.warn( "Couldn\'t save statistic " + ((class_nd) var3.getKey()).e() + ": error serializing progress", var6); } var1.add(((class_nd) var3.getKey()).e, var4); } else { var1.addProperty( ((class_nd) var3.getKey()).e, Integer.valueOf(((class_nf) var3.getValue()).a())); } } return var1.toString(); }
public RollupTask parseRollupTask(String json) throws BeanValidationException, QueryException { JsonParser parser = new JsonParser(); JsonObject taskObject = parser.parse(json).getAsJsonObject(); RollupTask task = parseRollupTask(taskObject, ""); task.addJson(taskObject.toString().replaceAll("\\n", "")); return task; }
@Path("/create/{ObjID}/{ObjInsId}") @POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public Response sendCreate( @PathParam("ObjID") String objectId, @PathParam("ObjInsId") String objectInstanceId, @QueryParam("ep") String endPoint, String value) throws InterruptedException { String string = objectId + "/" + objectInstanceId; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("operation", "create"); jsonObject.addProperty("directory", string); jsonObject.addProperty("value", value); Info.setInfo(endPoint, jsonObject.toString()); CountDownLatch signal = Info.getCountDown(endPoint); if (signal == null) { return Response.status(200).entity("Devices not registered yet").build(); } signal.countDown(); CountDownLatch signalRead = new CountDownLatch(1); Info.setCountDownLatchMessageMap(endPoint, signalRead); signalRead.await(); return Response.status(200).entity("creation success").build(); }
public byte[] getJsonByteArray() { if (mJsonObject == null) { return null; } final String toString = mJsonObject.toString(); return toString.getBytes(); }
/** * Builds the start message. * * @param options the options * @return the request */ private String buildStartMessage(RecognizeOptions options) { JsonObject startMessage = new JsonParser().parse(new Gson().toJson(options)).getAsJsonObject(); startMessage.remove(MODEL); startMessage.addProperty(ACTION, START); return startMessage.toString(); }
private void getStats(WebSocketSession session) { try { Map<String, Stats> wr_stats = webRtcEndpoint.getStats(); for (Stats s : wr_stats.values()) { switch (s.getType()) { case endpoint: EndpointStats end_stats = (EndpointStats) s; double e2eVideLatency = end_stats.getVideoE2ELatency() / 1000000; JsonObject response = new JsonObject(); response.addProperty("id", "videoE2Elatency"); response.addProperty("message", e2eVideLatency); sendMessage(session, new TextMessage(response.toString())); break; default: break; } } } catch (Throwable t) { log.error("Exception getting stats...", t); } }
public String create() { try { JsonObject gistJson = new JsonObject(); gistJson.addProperty("description", this.getDescription()); gistJson.addProperty("public", this.isPublic()); JsonObject filesJson = new JsonObject(); for (int i = 0; i < getFiles().length; i++) { GistFile gistFile = getFiles()[i]; JsonObject file = new JsonObject(); file.addProperty("content", gistFile.getContent()); String name = gistFile.getFileName(); filesJson.add( (name == null || name.isEmpty() ? "" : name + "-") + date.replace(' ', '_'), file); } gistJson.add("files", filesJson); HttpResponse<JsonNode> response = Unirest.post(GitHub.GISTS_API_URL) .header( "authorization", "token " + Nexus.getInstance().getGitHubConfig().getNexusGitHubApiKey()) .header("accept", "application/json") .header("content-type", "application/json; charset=utf-8") .body(gistJson.toString()) .asJson(); return response.getBody().getObject().getString("html_url"); } catch (UnirestException e) { throw new GistException("Failed to Gist!", e); } }
private void saveSetup() { RequestProperties headers = null; if (this.getString("item_id") == null) { headers = new RequestProperties.Builder() .method("POST") .endPoint("api/v/1/data/" + collectionId) .body(this.json) .build(); } else { // Create Payload object JsonObject payload = new JsonObject(); payload.addProperty("$set", this.changes.toString()); JsonObject query = new JsonObject(); query.addProperty("item_id", this.getString("item_id")); payload.addProperty("query", query.toString()); headers = new RequestProperties.Builder() .method("PUT") .endPoint("api/v/1/data/" + collectionId) .body(payload) .build(); } request.setHeaders(headers); }
@Override public void run() { try { CommandsController cc = hiveClient.getCommandsController(); DeviceCommand command = new DeviceCommand(); command.setCommand(COMMAND); JsonObject commandParams = new JsonObject(); if (isItGreenTurn) { commandParams.addProperty(LED_TYPE, LED_GREEN); if (isGreen) { commandParams.addProperty(LED_STATE, 0); } else { commandParams.addProperty(LED_STATE, 1); } isGreen = !isGreen; } else { commandParams.addProperty(LED_TYPE, LED_RED); if (isRed) { commandParams.addProperty(LED_STATE, 0); } else { commandParams.addProperty(LED_STATE, 1); } isRed = !isRed; } isItGreenTurn = !isItGreenTurn; command.setParameters(new JsonStringWrapper(commandParams.toString())); cc.insertCommand(uuid, command, commandUpdatesHandler); print("The command {} will be sent to all available devices", command.getCommand()); } catch (HiveException e) { print(e.getMessage()); } }
@POST @Path("action") public String action( @FormParam("element_1") double n1, @FormParam("element_2") double n2, @FormParam("element_3") String s) { try { MemcachedClient client = MccFactory.getConst("localhost").getMemcachedClient(); JsonObject innerObject = new JsonObject(); innerObject.addProperty("key", s); innerObject.addProperty("firstNum", n1); innerObject.addProperty("secondNum", n2); client.add(s, 30000, innerObject.toString()); String keys = (String) client.get("mykeys"); keys = (keys == null) ? "" : keys; keys += s + "/"; client.replace("mykeys", 30000, keys); } catch (Exception e) { e.printStackTrace(); return getStringStackTrace(e); } return "String: " + s + ". First number = " + n1 + ", Second number = " + n2; }
private void createDatabaseFile() { try { fos = this.context.openFileOutput(this.databaseName, Context.MODE_APPEND); JsonObject dataObject = new JsonObject(); dataObject.addProperty( "ANDROID_ID", Settings.Secure.getString(this.context.getContentResolver(), Settings.Secure.ANDROID_ID)); dataObject.addProperty( this.COLUMN_TIME_OFFSET, TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000 / 60); try { dataObject.addProperty("FUNF_VERSION", FunfManager.funfManager.getVersion()); } catch (NullPointerException e) { } try { dataObject.addProperty( "APPLICATION_VERSION", FunfManager.funfManager.getApplicationVersion()); } catch (NullPointerException e) { } fos.write((dataObject.toString() + "\n").getBytes()); } catch (IOException e) { e.printStackTrace(); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String blobKey = req.getParameter("blobKey"); String path = req.getParameter("path"); if (path != null && path.trim().length() > 0) { JsonObject retObj = new JsonObject(); String uploadBlobPath = BlobstoreServiceFactory.getBlobstoreService() .createUploadUrl(URLDecoder.decode(path), UploadOptions.Builder.withDefaults()); retObj.addProperty("result", "success"); retObj.addProperty("path", URLEncoder.encode(uploadBlobPath)); if (retObj.get("result") == null) { retObj.addProperty("result", "fail"); } resp.getWriter().write(retObj.toString()); } else if (blobKey != null) { BlobstoreServiceFactory.getBlobstoreService().serve(new BlobKey(blobKey), resp); } }