private void getTrafficSpots() { controller.showProgressBar(); String uploadWebsite = "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43"; String[] ArrayOfData = null; StreamConnection c = null; InputStream s = null; StringBuffer b = new StringBuffer(); String url = uploadWebsite; System.out.print(url); try { c = (StreamConnection) Connector.open(url); s = c.openDataInputStream(); int ch; int k = 0; while ((ch = s.read()) != -1) { System.out.print((char) ch); b.append((char) ch); } // System.out.println("b"+b); try { JSONObject ff1 = new JSONObject(b.toString()); String data1 = ff1.getString("locations"); JSONArray jsonArray1 = new JSONArray(data1); Vector TrafficStatus = new Vector(); for (int i = 0; i < jsonArray1.length(); i++) { System.out.println(jsonArray1.getJSONArray(i).getString(3)); double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1)); double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2)); System.out.println(aDoubleLat + " " + aDoubleLon); TrafficStatus.addElement( new LocationPointer( jsonArray1.getJSONArray(i).getString(3), (float) aDoubleLon, (float) aDoubleLat, 1, true)); } controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus)); } catch (Exception E) { controller.setCurrentScreen(traf); new Thread() { public void run() { controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO); } }.start(); } } catch (Exception e) { controller.setCurrentScreen(traf); new Thread() { public void run() { controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO); } }.start(); } }
@SuppressWarnings({"unused", "unchecked"}) public final JSONObject object() throws ParseException { final JSONObject json = new JSONObject(); String key; Object value; key = objectKey(); jj_consume_token(EQUALS); value = value(); json.put(key, value); key = null; value = null; label_2: while (true) { if (jj_2_1(2)) {; } else { break label_2; } jj_consume_token(COMMA); key = objectKey(); jj_consume_token(EQUALS); value = value(); json.put(key, value); key = null; value = null; } { if (true) return json; } throw new Error("Missing return statement in function"); }
@SuppressWarnings({"unchecked", "unused"}) public final JSONObject innerMap() throws ParseException { final JSONObject json = new JSONObject(); String key; Object value; key = objectKey(); jj_consume_token(EQUALS); value = value(); json.put(key, value); key = null; value = null; label_1: while (true) { switch (jj_nt.kind) { case SLASH:; break; default: jj_la1[1] = jj_gen; break label_1; } jj_consume_token(SLASH); jj_consume_token(COMMA); key = objectKey(); jj_consume_token(EQUALS); value = value(); json.put(key, value); key = null; value = null; } { if (true) return json; } throw new Error("Missing return statement in function"); }
public void trapException(String output) throws CrowdFlowerException { try { JSONObject error = new JSONObject(output); if (error.has("error")) { throw new CrowdFlowerException(error.get("error").toString()); } } catch (JSONException e) { // ignore } }
/** * Sends command to retrieve phones list. * * @return is command successful. */ @SuppressWarnings("unchecked") private boolean getPhoneList() { JSONObject obj = new JSONObject(); try { obj.put("class", "phones"); obj.put("function", "getlist"); return send(obj); } catch (Exception e) { logger.error("Error retrieving phones"); return false; } }
/** Handles new incoming object. */ private void handle(JSONObject incomingObject) { if (!incomingObject.containsKey("class")) return; try { String classField = (String) incomingObject.get("class"); if (classField.equals("loginko")) { showError(null, null, "Unauthorized. Cannot login: "******"errorstring")); logger.error("Error login: "******"errorstring")); destroy(); return; } else if (classField.equals("login_id_ok")) { SipAccountIDImpl accountID = (SipAccountIDImpl) sipProvider.getAccountID(); boolean useSipCredentials = accountID.isClistOptionUseSipCredentials(); String password; if (useSipCredentials) { password = SipActivator.getProtocolProviderFactory().loadPassword(accountID); } else { password = accountID.getClistOptionPassword(); } if (!authorize((String) incomingObject.get("sessionid"), password)) logger.error("Error login authorization!"); return; } else if (classField.equals("login_pass_ok")) { if (!sendCapas((JSONArray) incomingObject.get("capalist"))) logger.error("Error send capas!"); return; } else if (classField.equals("login_capas_ok")) { if (!sendFeatures( (String) incomingObject.get("astid"), (String) incomingObject.get("xivo_userid"))) logger.error("Problem send features get!"); return; } else if (classField.equals("features")) { if (!getPhoneList()) logger.error("Problem send get phones!"); return; } else if (classField.equals("phones")) { phonesRecieved(incomingObject); return; } else if (classField.equals("disconn")) { destroy(); return; } else { if (logger.isTraceEnabled()) logger.trace("unhandled classField: " + incomingObject); return; } } catch (Throwable t) { logger.error("Error handling incoming object", t); } }
/** * Send needed command for features. * * @param astid param from previous command. * @param xivoUserId param from previous command. * @return is command successful. */ @SuppressWarnings("unchecked") private boolean sendFeatures(String astid, String xivoUserId) { if (connection == null || astid == null || xivoUserId == null) return false; JSONObject obj = new JSONObject(); try { obj.put("class", "featuresget"); obj.put("userid", astid + "/" + xivoUserId); return send(obj); } catch (Exception e) { logger.error("Error send features get command", e); return false; } }
/** * Sends password command. * * @param sessionId the session id from previous command. * @param password the password to authorize. * @return is command successful. */ @SuppressWarnings("unchecked") private boolean authorize(String sessionId, String password) { if (connection == null || sessionId == null || password == null) return false; JSONObject obj = new JSONObject(); try { obj.put("class", "login_pass"); obj.put("hashedpassword", Sha1Crypto.encode(sessionId + ":" + password)); return send(obj); } catch (Exception e) { logger.error("Error login with password", e); return false; } }
private void printObj(JSONObject jObj, PrintWriter writer) { try { // System.out.println(jObj.toString(3)); writer.print(jObj.toString(3)); } catch (JSONException e) { System.out.println("could to to string json object"); } }
/** * Returns control when task is complete. * * @param json * @param logger */ private String waitForDeploymentCompletion(JSON json, OctopusApi api, Log logger) { final long WAIT_TIME = 5000; final double WAIT_RANDOM_SCALER = 100.0; JSONObject jsonObj = (JSONObject) json; String id = jsonObj.getString("TaskId"); Task task = null; String lastState = "Unknown"; try { task = api.getTask(id); } catch (IOException ex) { logger.error("Error getting task: " + ex.getMessage()); return null; } logger.info("Task info:"); logger.info("\tId: " + task.getId()); logger.info("\tName: " + task.getName()); logger.info("\tDesc: " + task.getDescription()); logger.info("\tState: " + task.getState()); logger.info("\n\nStarting wait..."); boolean completed = task.getIsCompleted(); while (!completed) { try { task = api.getTask(id); } catch (IOException ex) { logger.error("Error getting task: " + ex.getMessage()); return null; } completed = task.getIsCompleted(); lastState = task.getState(); logger.info("Task state: " + lastState); if (completed) { break; } try { Thread.sleep(WAIT_TIME + (long) (Math.random() * WAIT_RANDOM_SCALER)); } catch (InterruptedException ex) { logger.info("Wait interrupted!"); logger.info(ex.getMessage()); completed = true; // bail out of wait loop } } logger.info("Wait complete!"); return lastState; }
/** * Performs a test by sending HTTP Gets to the URL, and records the number of bytes returned. Each * test results are documented and displayed in standard out with the following information: * * <p>URL - The source URL of the test REQ CNT - How many times this test has run START - The * start time of the last test run STOP - The stop time of the last test run THREAD - The thread * id handling this test case RESULT - The result of the test. Either the number of bytes returned * or an error message. */ private void doTest() { String result = ""; this.reqCount++; // Connect and run test steps Date startTime = new Date(); try { ClientResource client = new ClientResource(this.myURL); // place order JSONObject json = new JSONObject(); json.put("payment", "quarter"); json.put("action", "place-order"); client.post(new JsonRepresentation(json), MediaType.APPLICATION_JSON); // Get Gumball Count Representation result_string = client.get(); JSONObject json_count = new JSONObject(result_string.getText()); result = Integer.toString((int) json_count.get("count")); } catch (Exception e) { result = e.toString(); } finally { Date stopTime = new Date(); // Print Report of Result: System.out.println( "======================================\n" + "URL => " + this.myURL + "\n" + "REQ CNT => " + this.reqCount + "\n" + "START => " + startTime + "\n" + "STOP => " + stopTime + "\n" + "THREAD => " + Thread.currentThread().getName() + "\n" + "RESULT => " + result + "\n"); } }
// El string debe estar em formato json public boolean updateRegistry(String dataJson) { try { // Crea objeto json con string por parametro JSONObject json = new JSONObject(dataJson); // Obtiene el array de Registos JSONArray arr = json.getJSONArray("Registry"); // Recorre el array for (int i = 0; i < arr.length(); i++) { // Obtiene los datos idSensor y value int idSensor = arr.getJSONObject(i).getInt("idSensor"); int value = arr.getJSONObject(i).getInt("value"); // Recorre la configuracion de registro for (RegistryConf reg : registryConf) { // Se fija si el registro corresponde a esta configuracion if (reg.getIdSensor() == idSensor) { // Checkea el criterio para guardar, o no en la BD // Checkea tambien si el valor es igual al anterior if (reg.getSaveTypeString() == "ONCHANGE" && lastRead.get(idSensor) != value) { // Actualizo la ultima lectura y guardo en la BD lastRead.put(idSensor, value); saveRegistry(idSensor, value); } else if (reg.getSaveTypeString() == "ONTIME") { // Variables auxiliares, para checkear tiempo Long auxLong = System.currentTimeMillis() / 1000; int now = auxLong.intValue(); int timeToSave = lastRead.get(idSensor) + reg.getValue(); // Checkea si ya es tiempo para guerdar un nuevo registro if (now >= timeToSave) { // Actualizo el ultimo guardado lastRead.put(idSensor, now); saveRegistry(idSensor, value); } } } } } } catch (Exception e) { e.printStackTrace(); } return false; }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, MongoException, DuplicateKeyException, UnknownHostException { // TODO Auto-generated method stub doGet(request, response); StringBuilder buffer = new StringBuilder(); BufferedReader reader = request.getReader(); String uname = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); System.out.println(uname + " " + password + " " + email); /*String line; while((line=reader.readLine())!=null){ buffer.append(line); } String data = buffer.toString(); System.out.println(data); data = "{\"p\":\"N\",\"c\":\"W\"}";*/ // System.out.println(data); // JSONObject params = (JSONObject)JSON.parse(data); JSONObject params = new JSONObject(); params.put("username", uname); params.put("password", password); BasicDBObject user1 = new BasicDBObject(params); for (Object key : params.keySet().toArray()) { user1.put(key.toString(), params.get(key)); } // System.out.println(user1.toJson()); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds035014.mongolab.com:35014/vikas2"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("users"); users.insert(user1); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); }
@RequestMapping( value = "/getCityApi", method = {RequestMethod.GET, RequestMethod.POST}) public String getCityApi( HttpServletRequest request, @RequestParam(value = "locationname") String locationname, ModelMap model) { Map<Object, Object> map = new HashMap<Object, Object>(); JSONArray jSONArray = new JSONArray(); try { String status = "active"; List<City> cityList = cityService.getCityApi(locationname, status); if (cityList != null && cityList.size() > 0) { for (int i = 0; i < cityList.size(); i++) { City city = (City) cityList.get(i); String cityName = (String) city.getCity(); String stateName = (String) city.getState(); int ID = (Integer) (city.getId()); JSONObject jSONObject = new JSONObject(); jSONObject.put("id", ID); jSONObject.put("text", cityName); jSONArray.put(jSONObject); } utilities.setSuccessResponse(response, jSONArray.toString()); } else { throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA); } } catch (Exception ex) { logger.error("getCity :" + ex.getMessage()); utilities.setErrResponse(ex, response); } model.addAttribute("model", jSONArray.toString()); return "home"; }
public AppUrlVerififcation verify(String appUrl) { if (DISABLE_APP_URL_VALIDATION) { return AppUrlVerififcation.ok(appUrl); } try { JSONObject json = new SimpleJsonClient2().get(appUrl + "/setup/poll"); if (!json.getString("handler").equals("medic-api")) return AppUrlVerififcation.failure(appUrl, errAppUrl_appNotFound); if (!json.getBoolean("ready")) return AppUrlVerififcation.failure(appUrl, errAppUrl_apiNotReady); return AppUrlVerififcation.ok(appUrl); } catch (MalformedURLException ex) { // seems unlikely, as we should have verified this already return AppUrlVerififcation.failure(appUrl, errInvalidUrl); } catch (JSONException ex) { return AppUrlVerififcation.failure(appUrl, errAppUrl_appNotFound); } catch (IOException ex) { if (DEBUG) ex.printStackTrace(); return AppUrlVerififcation.failure(appUrl, errAppUrl_serverNotFound); } }
public void registrarUsuario() { String dato = ""; JSONParser parser = new JSONParser(); try { while (true) { dato = dis.readUTF(); String usuario = ""; String contraseña = ""; String contra = ""; if (dato.equals("Usuario")) { while (true) { usuario = dis.readUTF(); if (usuario != null) { JSONObject user = new JSONObject(); user.put(usuario, null); FileWriter escribir = new FileWriter("texto.txt"); BufferedWriter bw = new BufferedWriter(escribir); PrintWriter pw = new PrintWriter(bw); pw.write(user.toJSONString()); pw.close(); bw.close(); while (true) { contra = dis.readUTF(); if (contra.equals("Contraseña")) { while (true) { contraseña = dis.readUTF(); if (contraseña != null) { Object obj = parser.parse(new FileReader("texto.txt")); JSONObject asignaPass = (JSONObject) obj; asignaPass.put(usuario, contra); FileWriter escribir2 = new FileWriter("texto.txt"); BufferedWriter bw2 = new BufferedWriter(escribir2); PrintWriter pw2 = new PrintWriter(bw2); pw2.write(asignaPass.toJSONString()); bw2.newLine(); pw2.close(); bw2.close(); break; } } break; } } break; } } break; } } } catch (Exception e) { } }
private JSONObject endGame(int gameCount) { Random randomNum = new Random(); GameInfo gameInfo; JSONObject jObj = new JSONObject(); JSONObject action = new JSONObject(); int game; String status; game = getRandomGame(gameCount); gameInfo = gameRecord.get(game); gameInfo.incrementCount(); if (gameInfo.getCount() < 9) { return moveUser(gameCount); } if (gameInfo.getPoints() > 40 || gameInfo.getPoints() < -40) { status = "WIN"; } else { status = "LOSS"; } try { jObj.put("game", game); action.put("actionType", "gameEnd"); action.put("gameStatus", status); action.put("actionNumber", gameInfo.getCount()); action.put("points", gameInfo.getPoints()); jObj.put("action", action); jObj.put("user", gameInfo.getUser()); userIds[gameInfo.getId()] = false; gameRecord.remove(game); } catch (JSONException e) { System.out.println("could not put"); } return jObj; }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection(Utility.connection, Utility.username, Utility.password); String email = request.getParameter("email_id"); String number = ""; boolean exists = false; String user_name = ""; int user_id = -1; String str1 = "SELECT USER_ID,NAME,PHONE_NUMBER FROM USERS WHERE EMAIL_ID=?"; PreparedStatement prep1 = con.prepareStatement(str1); prep1.setString(1, email); ResultSet rs1 = prep1.executeQuery(); if (rs1.next()) { exists = true; user_id = rs1.getInt("USER_ID"); user_name = rs1.getString("NAME"); number = rs1.getString("PHONE_NUMBER"); } int verification = 0; JSONObject data = new JSONObject(); if (exists) { verification = (int) (Math.random() * 9535641 % 999999); System.out.println("Number " + number + "\nVerification: " + verification); SMSProvider.sendSMS( number, "Your One Time Verification Code for PeopleConnect Is " + verification); } data.put("user_name", user_name); data.put("user_id", user_id); data.put("verification_code", "" + verification); data.put("phone_number", number); String toSend = data.toJSONString(); out.print(toSend); System.out.println(toSend); } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
/** * Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, * or String, or the JSONObject.NULL object. * * @return An object. * @throws JSONException If syntax error. */ public Object nextValue() throws JSONException { char c = nextClean(); String string; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuilder sb = new StringBuilder(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); string = sb.toString().trim(); if (string.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
public static JSONValue parseJSONValue(ParseState parseState) { if (parseState.skipWhite()) { char c = parseState.current(); switch (c) { case '{': return JSONObject.parseJSON(parseState); case '"': return JSONString.parseJSON(parseState); case '[': return JSONArray.parseJSON(parseState); case 'n': return JSONNull.parseJSON(parseState); case 't': case 'f': return JSONBoolean.parseJSON(parseState); default: if ((c >= '0' && c <= '9') || c == '-' || c == '.' || c == 'N') // NaN ok return JSONNumber.parseJSON(parseState); break; } } return null; }
/** * Sends login command. * * @param capalistParam param from previous command. * @return is command successful. */ @SuppressWarnings("unchecked") private boolean sendCapas(JSONArray capalistParam) { if (connection == null || capalistParam == null || capalistParam.isEmpty()) return false; JSONObject obj = new JSONObject(); try { obj.put("class", "login_capas"); obj.put("capaid", capalistParam.get(0)); obj.put("lastconnwins", "false"); obj.put("loginkind", "agent"); obj.put("state", ""); return send(obj); } catch (Exception e) { logger.error("Error login", e); return false; } }
private JSONObject createNewUser(int gameId) { int userId; JSONObject jObj = new JSONObject(); JSONObject action = new JSONObject(); Random randomNum = new Random(); userId = randomNum.nextInt(max_users) + 1; while (userIds[userId] == true) { userId = randomNum.nextInt(max_users) + 1; } userIds[userId] = true; try { jObj.put("game", gameId); action.put("actionType", "gameStart"); action.put("actionNumber", 1); jObj.put("action", action); jObj.put("user", "u" + userId); } catch (JSONException e) { System.out.println("could not put"); } gameRecord.put(gameId, new GameInfo("u" + userId, userId)); return jObj; }
/** * Sends login command. * * @param username the username. * @return is command successful. */ @SuppressWarnings("unchecked") private boolean login(String username) { if (connection == null || username == null) return false; JSONObject obj = new JSONObject(); try { obj.put("class", "login_id"); obj.put("company", "Jitsi"); String os = "x11"; if (OSUtils.IS_WINDOWS) os = "win"; else if (OSUtils.IS_MAC) os = "mac"; obj.put("ident", username + "@" + os); obj.put("userid", username); obj.put("version", "9999"); obj.put("xivoversion", "1.1"); return send(obj); } catch (Exception e) { logger.error("Error login", e); return false; } }
/** * Parses the given http response. * * @param response the http response to parse * @return the new account */ private NewAccount parseHttpResponse(String response) { NewAccount newAccount = null; try { JSONObject jsonObject = (JSONObject) JSONValue.parseWithException(response); boolean isSuccess = (Boolean) jsonObject.get("success"); if (isSuccess) { newAccount = new NewAccount( (String) jsonObject.get("sip_address"), passField.getPassword(), null, (String) jsonObject.get("outbound_proxy")); String xcapRoot = (String) jsonObject.get("xcap_root"); // as sip2sip adds @sip2sip.info at the end of the // xcap_uri but doesn't report it in resullt after // creating account, we add it String domain = null; int delimIndex = newAccount.getUserName().indexOf("@"); if (delimIndex != -1) { domain = newAccount.getUserName().substring(delimIndex); } if (domain != null) { if (xcapRoot.endsWith("/")) xcapRoot = xcapRoot.substring(0, xcapRoot.length() - 1) + domain; else xcapRoot += domain; } newAccount.setXcapRoot(xcapRoot); } else { showErrorMessage((String) jsonObject.get("error_message")); } } catch (Throwable e1) { if (logger.isInfoEnabled()) logger.info("Failed Json parsing.", e1); } return newAccount; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); String q = request.getParameter("q"); if (q == null) { writer.println("ERROR: q has no value."); writer.close(); return; } ResultBundle[] results = Map.getResults(q.toLowerCase()); writer.println("STATUS: " + results.length + " results for the query " + q + "!"); for (ResultBundle rb : results) { JSONObject j = new JSONObject(); j.put("thumbnail", rb.getThumbnail()); j.put("title", rb.getTitle()); j.put("description", rb.getDescription()); j.put("url", rb.getUrl()); writer.println(j.toString()); } writer.close(); }
public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) { StringBuffer bodyContent = null; OutputStream out = null; PrintWriter writer = null; String serviceKey = null; try { BufferedReader in = req.getReader(); String line = null; while ((line = in.readLine()) != null) { if (bodyContent == null) bodyContent = new StringBuffer(); bodyContent.append(line); } } catch (Exception e) { } try { if (requireSession) { // check to see if there was a session created for this request // if not assume it was from another domain and blow up // Wrap this to prevent Portlet exeptions HttpSession session = req.getSession(false); if (session == null) { res.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } serviceKey = req.getParameter("id"); // only to preven regressions - Remove before 1.0 if (serviceKey == null) serviceKey = req.getParameter("key"); // check if the services have been loaded or if they need to be reloaded if (services == null || configUpdated()) { getServices(res); } String urlString = null; String xslURLString = null; String userName = null; String password = null; String format = "json"; String callback = req.getParameter("callback"); String urlParams = req.getParameter("urlparams"); String countString = req.getParameter("count"); // encode the url to prevent spaces from being passed along if (urlParams != null) { urlParams = urlParams.replace(' ', '+'); } try { if (services.has(serviceKey)) { JSONObject service = services.getJSONObject(serviceKey); // default to the service default if no url parameters are specified if (urlParams == null && service.has("defaultURLParams")) { urlParams = service.getString("defaultURLParams"); } String serviceURL = service.getString("url"); // build the URL if (urlParams != null && serviceURL.indexOf("?") == -1) { serviceURL += "?"; } else if (urlParams != null) { serviceURL += "&"; } String apikey = ""; if (service.has("username")) userName = service.getString("username"); if (service.has("password")) password = service.getString("password"); if (service.has("apikey")) apikey = service.getString("apikey"); urlString = serviceURL + apikey; if (urlParams != null) urlString += "&" + urlParams; if (service.has("xslStyleSheet")) { xslURLString = service.getString("xslStyleSheet"); } } // code for passing the url directly through instead of using configuration file else if (req.getParameter("url") != null) { String serviceURL = req.getParameter("url"); // build the URL if (urlParams != null && serviceURL.indexOf("?") == -1) { serviceURL += "?"; } else if (urlParams != null) { serviceURL += "&"; } urlString = serviceURL; if (urlParams != null) urlString += urlParams; } else { writer = res.getWriter(); if (serviceKey == null) writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required."); else writer.write( "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not found."); writer.flush(); return; } } catch (Exception ex) { getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex); } Map paramsMap = new HashMap(); paramsMap.put("format", format); // do not allow for xdomain unless the context level setting is enabled. if (callback != null && allowXDomain) { paramsMap.put("callback", callback); } if (countString != null) { paramsMap.put("count", countString); } InputStream xslInputStream = null; if (urlString == null) { writer = res.getWriter(); writer.write( "XmlHttpProxyServlet parameters: id[Required] urlparams[Optional] format[Optional] callback[Optional]"); writer.flush(); return; } // default to JSON res.setContentType(responseContentType); out = res.getOutputStream(); // get the stream for the xsl stylesheet if (xslURLString != null) { // check the web root for the resource URL xslURL = null; xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString); // if not in the web root check the classpath if (xslURL == null) { xslURL = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString); } if (xslURL != null) { xslInputStream = xslURL.openStream(); } else { String message = "Could not locate the XSL stylesheet provided for service id " + serviceKey + ". Please check the XMLHttpProxy configuration."; getLogger().severe(message); try { out.write(message.getBytes()); out.flush(); return; } catch (java.io.IOException iox) { } } } if (!isPost) { xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password); } else { if (bodyContent == null) getLogger() .info( "XmlHttpProxyServlet attempting to post to url " + urlString + " with no body content"); xhp.doPost( urlString, out, xslInputStream, paramsMap, bodyContent.toString(), req.getContentType(), userName, password); } } catch (Exception iox) { iox.printStackTrace(); getLogger().severe("XmlHttpProxyServlet: caught " + iox); try { writer = res.getWriter(); writer.write(iox.toString()); writer.flush(); } catch (java.io.IOException ix) { ix.printStackTrace(); } return; } finally { try { if (out != null) out.close(); if (writer != null) writer.close(); } catch (java.io.IOException iox) { } } }
private JSONObject specialMove(int gameCount) { Random randomNum = new Random(); GameInfo gameInfo; JSONObject jObj = new JSONObject(); JSONObject action = new JSONObject(); int game; int addPoints; int special; // Gets random number to denote which game to use action on game = getRandomGame(gameCount); gameInfo = gameRecord.get(game); // Checks if all specials are used if (gameInfo.checkSpecial()) { return moveUser(gameCount); } // Gets random number to denote which special move to use special = randomNum.nextInt(4); while (gameInfo.checkSpecialMove(special)) { special = randomNum.nextInt(4); } gameInfo.useSpecialMove(special); addPoints = randomNum.nextInt(41) - 20; gameInfo.addPoints(addPoints); gameInfo.incrementCount(); try { jObj.put("game", game); action.put("actionType", "specialMove"); action.put("actionNumber", gameInfo.getCount()); action.put("pointsAdded", addPoints); if (special == SHUFFLE) { action.put("move", "Shuffle"); } else if (special == CLEAR) { action.put("move", "Clear"); } else if (special == INVERT) { action.put("move", "Invert"); } else { action.put("move", "Rotate"); } action.put("points", gameInfo.getPoints()); jObj.put("action", action); jObj.put("user", gameInfo.getUser()); } catch (JSONException e) { System.out.println("could not put"); } return jObj; }
private JSONObject moveUser(int gameCount) { Random randomNum = new Random(); GameInfo gameInfo; JSONObject jObj = new JSONObject(); JSONObject action = new JSONObject(); JSONObject coords = new JSONObject(); int game; int xCoord; int yCoord; int addPoints; // Gets random number to denote which game to use action on game = getRandomGame(gameCount); xCoord = randomNum.nextInt(20) + 1; yCoord = randomNum.nextInt(20) + 1; addPoints = randomNum.nextInt(41) - 20; gameInfo = gameRecord.get(game); gameInfo.addPoints(addPoints); gameInfo.incrementCount(); try { jObj.put("game", game); coords.put("x", xCoord); coords.put("y", yCoord); action.put("actionType", "Move"); action.put("actionNumber", gameInfo.getCount()); action.put("location", coords); action.put("pointsAdded", addPoints); action.put("points", gameInfo.getPoints()); jObj.put("action", action); jObj.put("user", gameInfo.getUser()); } catch (JSONException e) { System.out.println("could not put"); } return jObj; }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setHeader("Cache-Control", "nocache"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); StringWriter result = new StringWriter(); // get received JSON data from request BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String postData = ""; if (br != null) { postData = br.readLine(); } try { JSONObject json = (JSONObject) new JSONParser().parse(postData); JSONObject resultObj = new JSONObject(); JSONArray list = new JSONArray(); List<Tracking> trackingList = new ArrayList<Tracking>(); // get the website list if (json.get("type").equals("websiteslist")) { trackingList = trackingDao.websiteList(pool); for (Tracking item : trackingList) { list.add(item.getWebsite()); } } // render report else if (json.get("type").equals("submit")) { if (json.get("criteria").equals("date")) { // render repoty by date trackingList = trackingDao.getListByDate(pool, json.get("date").toString()); } else if (json.get("criteria").equals("daterange")) { // render repoty by date range trackingList = trackingDao.getListByDateRange( pool, json.get("fromdate").toString(), json.get("todate").toString()); } else if (json.get("criteria").equals("website")) { // render repoty by website String website = (json.get("website") == null ? "" : json.get("website").toString()); trackingList = trackingDao.getListByWebsite(pool, website); } for (Tracking item : trackingList) { JSONObject trackingObj = new JSONObject(); trackingObj.put("date", item.getDate()); trackingObj.put("website", item.getWebsite()); trackingObj.put("visit", item.getVisit()); list.add(trackingObj); } } resultObj.put("result", list); resultObj.writeJSONString(result); // finally output the json string out.print(result.toString()); } catch (ParseException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public Map getTaskMapBatch(String objectId) throws Exception { Map map = new HashMap(); String apiURL = "https://rally1.rallydev.com/slm/webservice/1.34/adhoc"; String requestJSON = "{" + "\"task\" : \"/task?query=(ObjectID%20=%20" + objectId + ")&fetch=true\"," + "\"userstory\" : \"/hierarchicalrequirement?query=(ObjectID%20=%20${task.WorkProduct.ObjectID})&fetch=FormattedID\"," + "\"timeentryitem\":\"/timeentryitem?query=(Task.ObjectID%20=%20" + objectId + ")&fetch=Values\"," + "\"timespent\":\"${timeentryitem.Values.Hours}\"" + "}"; log.info("apiURL=" + apiURL); log.info("requestJSON=" + requestJSON); String responseJSON = postRallyXML(apiURL, requestJSON); // log.info("responseJSON="+responseJSON); // Map jsonMap=JsonUtil.jsonToMap(responseJSON); JSONParser parser = new JSONParser(); Map jsonMap = (Map) parser.parse(responseJSON); // log.info("jsonMap="+jsonMap); String taskObjId = ""; String taskFormattedId = ""; String taskName = ""; String estimate = ""; String toDo = ""; String taskState = ""; String taskOwner = ""; String userstoryFormattedId = ""; // Get task info JSONObject taskMap = (JSONObject) jsonMap.get("task"); JSONArray taskArray = (JSONArray) taskMap.get("Results"); if (taskArray != null && taskArray.size() > 0) { JSONObject taskInfo = (JSONObject) taskArray.get(0); // log.info("taskMap="+taskMap); // log.info("taskInfo="+taskInfo); taskObjId = (taskInfo.get("ObjectID")).toString(); taskFormattedId = (taskInfo.get("FormattedID")).toString(); taskState = (taskInfo.get("State")).toString(); Object taskNameObj = taskInfo.get("Name"); taskName = taskNameObj == null ? "" : taskNameObj.toString(); Object estimateObject = taskInfo.get("Estimate"); estimate = estimateObject == null ? "" : estimateObject.toString(); Object toDoObject = taskInfo.get("ToDo"); toDo = toDoObject == null ? "" : toDoObject.toString(); JSONObject ownerMap = (JSONObject) taskInfo.get("Owner"); log.info("ownerMap=" + ownerMap); if (ownerMap != null) { taskOwner = (String) ownerMap.get("_refObjectName"); if (taskOwner == null) { taskOwner = ""; } } } // Get user story info JSONObject userstoryMap = (JSONObject) jsonMap.get("userstory"); JSONArray userstoryArray = (JSONArray) userstoryMap.get("Results"); if (userstoryArray != null && userstoryArray.size() > 0) { JSONObject userstoryInfo = (JSONObject) userstoryArray.get(0); userstoryFormattedId = (userstoryInfo.get("FormattedID")).toString(); log.info("userstoryFormattedId=" + userstoryFormattedId); } // Calculate timeSpent JSONArray timeSpentList = (JSONArray) jsonMap.get("timespent"); log.info("timeSpentList=" + timeSpentList); double timeSpent = 0.0; for (int i = 0; i < timeSpentList.size(); i++) { String timeSpentString = (String) timeSpentList.get(i); if (timeSpentString != null) { timeSpent += Double.parseDouble(timeSpentString); } } map.put("type", "task"); map.put("formattedId", taskFormattedId); map.put("usId", userstoryFormattedId); map.put("name", taskName); map.put("taskStatus", taskState); map.put("owner", taskOwner); map.put("taskEstimateTotal", estimate); map.put("taskRemainingTotal", toDo); map.put("taskTimeSpentTotal", "" + timeSpent); return map; }