List of usage examples for org.json.simple JSONArray size
public int size()
From source file:org.apache.tika.parser.captioning.tf.TensorflowRESTCaptioner.java
@Override public List<CaptionObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { List<CaptionObject> capObjs = new ArrayList<>(); try {//ww w .j a v a 2s . co m DefaultHttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(getApiUri(metadata)); try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) { //TODO: convert this to stream, this might cause OOM issue // InputStreamEntity is not working // request.setEntity(new InputStreamEntity(stream, -1)); IOUtils.copy(stream, byteStream); request.setEntity(new ByteArrayEntity(byteStream.toByteArray())); } HttpResponse response = client.execute(request); try (InputStream reply = response.getEntity().getContent()) { String replyMessage = IOUtils.toString(reply); if (response.getStatusLine().getStatusCode() == 200) { JSONObject jReply = (JSONObject) new JSONParser().parse(replyMessage); JSONArray jCaptions = (JSONArray) jReply.get("captions"); for (int i = 0; i < jCaptions.size(); i++) { JSONObject jCaption = (JSONObject) jCaptions.get(i); String sentence = (String) jCaption.get("sentence"); Double confidence = (Double) jCaption.get("confidence"); capObjs.add(new CaptionObject(sentence, LABEL_LANG, confidence)); } } else { LOG.warn("Status = {}", response.getStatusLine()); LOG.warn("Response = {}", replyMessage); } } } catch (Exception e) { LOG.warn(e.getMessage(), e); } return capObjs; }
From source file:forumbox.GetUserServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request/*w w w . ja v a 2 s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ // private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject IDlistobj = null; JSONObject postobj = null; JSONParser IDlistparser = new JSONParser(); JSONParser postParser = new JSONParser(); String[] Idlist = new String[10]; int count = 0; try { FileReader file1 = new FileReader( "/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/list.json"); Object obj = IDlistparser.parse(file1); IDlistobj = (JSONObject) obj; JSONArray list = (JSONArray) IDlistobj.get("list"); count = list.size() - 1; for (int i = 0; i < 10 && i <= count; i++) { Idlist[i] = list.get(count).toString(); count--; } } catch (Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("get ID is unsuccessful"); out.println(e); out.println("......................"); } // get the posts try { String[] idlist = new String[10]; String[] descriptionlist = new String[10]; String[] username = new String[10]; String[] titlelist = new String[10]; for (int i = 0; i < 10 && i <= count; i++) { FileReader file = new FileReader( "/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/" + Idlist[i] + ".json"); Object obj = postParser.parse(file); postobj = (JSONObject) obj; idlist[i] = postobj.get("id").toString(); descriptionlist[i] = postobj.get("description").toString(); username[i] = postobj.get("username").toString(); titlelist[i] = postobj.get("title").toString(); if (descriptionlist[i].length() > 200) { descriptionlist[i] = descriptionlist[i].substring(0, 199) + "...."; } } request.setAttribute("titlelist", titlelist); request.setAttribute("idlist", idlist); request.setAttribute("descriptionlist", descriptionlist); request.setAttribute("username", username); request.getRequestDispatcher("/indexpage.jsp").forward(request, response); } catch (Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("fetching post unsuccessful"); out.println(e); out.println("......................"); } }
From source file:control.ParametrizacionServlets.InsertarPuntoVertimientoContrato.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w. j a va2 s . com*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //Obtenemos el numero de contrato Double contrato = Double.parseDouble(request.getParameter("contrato")); //Obtenemos la cadena con la informacion y la convertimos en un //JSONArray String puntos = request.getParameter("puntos"); Object obj = JSONValue.parse(puntos); JSONArray jsonArray = new JSONArray(); jsonArray = (JSONArray) obj; //Recorremos el JSONArray y obtenemos la informacion. for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); String ubicacion = (String) jsonObject.get("ubicacion"); String latitud = (String) jsonObject.get("latitud"); String longitud = (String) jsonObject.get("longitud"); String observacion = (String) jsonObject.get("observacion"); String tipoEstructura = (String) jsonObject.get("tipoEstructura"); int estado = Integer.parseInt((String) jsonObject.get("estado")); //Creamos el manager y guardamos la informacion. PuntosVertimiento manager = new PuntosVertimiento(); manager.insertar(ubicacion, latitud, longitud, observacion, estado, contrato, tipoEstructura); } } catch (Exception ex) { //Logger.getLogger(InsertarActEconomica.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.algorithm.VehicleStatus.java
public VehicleStatus(JSONObject obj) { name = (String) obj.get("name"); id = (String) obj.get("vehicle.id"); state = Status.valueOf(((String) obj.get("state")).toUpperCase()); if (state == Status.ACTIVE || state == Status.SUSPENDED) { Double latitude = (Double) obj.get("latitude"); Double longitude = (Double) obj.get("longitude"); Double altitude = (Double) obj.get("altitude"); if (latitude != null && longitude != null && altitude != null) { position = new PolarCoordinate(latitude.doubleValue(), longitude.doubleValue(), altitude.doubleValue()); } else {/* ww w . ja v a 2 s .co m*/ position = null; } Double t = (Double) obj.get("tolerance"); tolerance = t != null ? t.doubleValue() : 5.0; JSONArray as = (JSONArray) obj.get("actions"); actions = new HashSet<String>(); if (as != null) { for (int k = 0; k < as.size(); ++k) { actions.add((String) as.get(k)); } } } }
From source file:com.piusvelte.webcaster.MediaLoader.java
@Override public List<Medium> loadInBackground() { List<Medium> media = new ArrayList<Medium>(); if (mediaUrl != null) { HttpURLConnection httpURLConnection; try {/*from www. jav a2 s . c om*/ String response; httpURLConnection = (HttpURLConnection) mediaUrl.openConnection(); InputStream in = new BufferedInputStream(httpURLConnection.getInputStream()); byte[] buffer = new byte[512]; ByteArrayOutputStream content = new ByteArrayOutputStream(); int readBytes = 0; while ((readBytes = in.read(buffer)) != -1) { content.write(buffer, 0, readBytes); } response = new String(content.toByteArray()); JSONParser jsonParser = new JSONParser(); JSONArray mediaJArr = (JSONArray) jsonParser.parse(response); Gson gson = new Gson(); for (int i = 0, s = mediaJArr.size(); i < s; i++) { media.add(gson.fromJson(mediaJArr.get(i).toString(), Medium.class)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return media; }
From source file:JavaCloud.Api.java
public ArrayList<Image> imageList(String type, String access, String[] prohibited_states) throws CoreException { JSONObject object = new JSONObject(); object.put("token", token); if (type != null) object.put("type", type); if (access != null) object.put("access", access); if (prohibited_states.length > 0) object.put("prohibited_states", prohibited_states); JSONArray jsonimages = (JSONArray) Utils.request(address, "/api/image/get_list/", object); ArrayList<Image> images = new ArrayList<Image>(); for (int i = 0; i < jsonimages.size(); i++) { images.add(new Image(address, token, (JSONObject) jsonimages.get(i))); }/*from w ww .ja v a 2 s . c om*/ return images; }
From source file:com.teozcommunity.teozfrank.duelme.util.UpdateChecker.java
/** * Query the API to find the latest approved file's details. *///from w ww. ja va2 s . c om public void query() { URL url = null; try { // Create the URL to query using the project's ID url = new URL(API_HOST + API_QUERY + projectID); } catch (MalformedURLException e) { // There was an error creating the URL e.printStackTrace(); return; } try { // Open a connection and query the project URLConnection conn = url.openConnection(); // Add the user-agent to identify the program conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)"); // Read the response of the query // The response will be in a JSON format, so only reading one line is necessary. final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); // Parse the array of files from the query's response JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() > 0) { // Get the newest file's details JSONObject latest = (JSONObject) array.get(array.size() - 1); // Get the version's title String versionName = (String) latest.get(API_NAME_VALUE); // Get the version's link String versionLink = (String) latest.get(API_LINK_VALUE); // Get the version's release type String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE); // Get the version's file name String versionFileName = (String) latest.get(API_FILE_NAME_VALUE); // Get the version's game version String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE); versionName = versionName.replaceAll("[a-zA-Z]", ""); versionName = versionName.replaceAll(" ", ""); String pluginVersion = plugin.getDescription().getVersion(); pluginVersion = pluginVersion.replaceAll("Alpha", ""); pluginVersion = pluginVersion.replaceAll("Beta", ""); pluginVersion = pluginVersion.replaceAll("Release", ""); pluginVersion = pluginVersion.replaceAll(" ", ""); if (!versionName.equals(pluginVersion)) { this.updateAvailable = true; SendConsoleMessage.info("There is a new update available!"); SendConsoleMessage.info("download it on bukkit dev " + ChatColor.YELLOW + "http://dev.bukkit.org/bukkit-plugins/duelme/"); } else { this.updateAvailable = false; SendConsoleMessage.info("plugin is up to date!"); } } else { System.out.println("There are no files for this project"); } } catch (IOException e) { // There was an error reading the query SendConsoleMessage.severe("There was an error checking for updates!"); return; } }
From source file:JavaCloud.Api.java
public ArrayList<String> functionList() throws CoreException { JSONObject object = new JSONObject(); object.put("token", token); JSONArray jsonfuncs = (JSONArray) Utils.request(address, "/api/api/list_functions/", object); ArrayList<String> functions = new ArrayList<String>(); for (int i = 0; i < jsonfuncs.size(); i++) { functions.add(jsonfuncs.get(i).toString()); }//from w ww.ja va 2 s . co m return functions; }
From source file:me.neatmonster.spacertk.plugins.templates.SBPlugin.java
/** * Creats a new Plugin/*from w w w.j ava 2 s . c om*/ * @param plugin JSONObject containing the raw information from BukGet */ public SBPlugin(final JSONObject plugin) { //TODO: should not crash if a field is missing name = (String) plugin.get("name"); status = (String) plugin.get("status"); link = (String) plugin.get("bukkitdev_link"); description = (String) plugin.get("desc"); final JSONArray categoriesJSONArray = (JSONArray) plugin.get("categories"); @SuppressWarnings("unchecked") final List<Object> categoriesListObject = categoriesJSONArray.subList(0, categoriesJSONArray.size()); for (final Object object : categoriesListObject) categories.add((String) object); final JSONArray versionsJSONArray = (JSONArray) plugin.get("versions"); @SuppressWarnings("unchecked") final List<Object> versionsListObject = versionsJSONArray.subList(0, versionsJSONArray.size()); final List<JSONObject> versionsListJSONObjects = new ArrayList<JSONObject>(); for (final Object object : versionsListObject) versionsListJSONObjects.add((JSONObject) object); for (final JSONObject object : versionsListJSONObjects) versions.add(new Version(object)); }
From source file:com.ebay.logstorm.server.platform.spark.SparkExecutionPlatform.java
@Override public synchronized void status(final PipelineExecutionEntity entity) throws Exception { String applicationId = entity.getProperties().getProperty("applicationId"); if (applicationId == null) { LOG.warn("get null applicationId, may be starting"); return;//www. j a va2 s.c om } entity.requireUpdate(true); int beginPort = MIN_REST_PORT; while (beginPort++ < MAX_REST_PORT) { String restURL = sparkRestUrl + ":" + beginPort + SPARK_REST_API_PATH + applicationId; try { URL url = new URL(restURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String statusStr = ""; String line; while (null != (line = br.readLine())) { statusStr += line + "\n"; } br.close(); entity.setDescription(statusStr); entity.setUrl(sparkRestUrl + ":" + beginPort + SPARK_JOB_PATH); LOG.info(statusStr); //parse more json fields later, just work now JSONParser parser = new JSONParser(); Object obj = parser.parse(statusStr); JSONObject jsonObject = (JSONObject) obj; if (applicationId.equals(jsonObject.get("id"))) { LOG.info("find application {} rest url {}", applicationId, restURL); } else { LOG.warn("wrong application {} rest url {}", applicationId, restURL); continue; } JSONArray a = (JSONArray) jsonObject.get("attempts"); for (int i = 0; i < a.size(); i++) { boolean finished = (boolean) ((JSONObject) a.get(i)).get("completed"); if (!finished) { entity.setStatus(PipelineExecutionStatus.RUNNING); return; } } entity.setStatus(PipelineExecutionStatus.STOPPED); return; } catch (Exception e) { } } entity.setStatus(PipelineExecutionStatus.STOPPED); LOG.warn("get status for application {} failed, assume stopped", applicationId); }