Example usage for org.json.simple JSONArray get

List of usage examples for org.json.simple JSONArray get

Introduction

In this page you can find the example usage for org.json.simple JSONArray get.

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:com.opensoc.parsing.parsers.BasicBroParser.java

@SuppressWarnings("unchecked")
public JSONObject parse(byte[] msg) {

    _LOG.trace("[OpenSOC] Starting to parse incoming message");

    String raw_message = null;/*w w  w .j av a 2s . c  o m*/

    try {

        raw_message = new String(msg, "UTF-8");
        _LOG.trace("[OpenSOC] Received message: " + raw_message);

        JSONObject cleaned_message = cleaner.Clean(raw_message);
        _LOG.debug("[OpenSOC] Cleaned message: " + raw_message);

        if (cleaned_message == null || cleaned_message.isEmpty())
            throw new Exception("Unable to clean message: " + raw_message);

        String key = cleaned_message.keySet().iterator().next().toString();

        if (key == null)
            throw new Exception("Unable to retrieve key for message: " + raw_message);

        JSONObject payload = (JSONObject) cleaned_message.get(key);

        String originalString = " |";
        for (Object k : payload.keySet()) {
            originalString = originalString + " " + k.toString() + ":" + payload.get(k).toString();
        }
        originalString = key.toUpperCase() + originalString;
        payload.put("original_string", originalString);

        if (payload == null)
            throw new Exception("Unable to retrieve payload for message: " + raw_message);

        if (payload.containsKey("ts")) {
            String ts = payload.remove("ts").toString();
            payload.put("timestamp", ts);
            _LOG.trace("[OpenSOC] Added ts to: " + payload);
        }

        if (payload.containsKey("id.orig_h")) {
            String source_ip = payload.remove("id.orig_h").toString();
            payload.put("ip_src_addr", source_ip);
            _LOG.trace("[OpenSOC] Added ip_src_addr to: " + payload);
        } else if (payload.containsKey("tx_hosts")) {
            JSONArray txHosts = (JSONArray) payload.remove("tx_hosts");
            if (txHosts != null && !txHosts.isEmpty()) {
                payload.put("ip_src_addr", txHosts.get(0));
                _LOG.trace("[OpenSOC] Added ip_src_addr to: " + payload);
            }
        }

        if (payload.containsKey("id.resp_h")) {
            String source_ip = payload.remove("id.resp_h").toString();
            payload.put("ip_dst_addr", source_ip);
            _LOG.trace("[OpenSOC] Added ip_dst_addr to: " + payload);
        } else if (payload.containsKey("rx_hosts")) {
            JSONArray rxHosts = (JSONArray) payload.remove("rx_hosts");
            if (rxHosts != null && !rxHosts.isEmpty()) {
                payload.put("ip_dst_addr", rxHosts.get(0));
                _LOG.trace("[OpenSOC] Added ip_dst_addr to: " + payload);
            }
        }

        if (payload.containsKey("id.orig_p")) {
            String source_port = payload.remove("id.orig_p").toString();
            payload.put("ip_src_port", source_port);
            _LOG.trace("[OpenSOC] Added ip_src_port to: " + payload);
        }
        if (payload.containsKey("id.resp_p")) {
            String dest_port = payload.remove("id.resp_p").toString();
            payload.put("ip_dst_port", dest_port);
            _LOG.trace("[OpenSOC] Added ip_dst_port to: " + payload);
        }

        //         if (payload.containsKey("host")) {
        //
        //            String host = payload.get("host").toString().trim();
        //            String tld = tldex.extractTLD(host);
        //
        //            payload.put("tld", tld);
        //            _LOG.trace("[OpenSOC] Added tld to: " + payload);
        //
        //         }
        //         if (payload.containsKey("query")) {
        //            String host = payload.get("query").toString();
        //            String[] parts = host.split("\\.");
        //            int length = parts.length;
        //            if (length >= 2) {
        //               payload.put("tld", parts[length - 2] + "."
        //                     + parts[length - 1]);
        //               _LOG.trace("[OpenSOC] Added tld to: " + payload);
        //            }
        //         }

        _LOG.trace("[OpenSOC] Inner message: " + payload);

        payload.put("protocol", key);
        _LOG.debug("[OpenSOC] Returning parsed message: " + payload);

        return payload;

    } catch (Exception e) {

        _LOG.error("Unable to Parse Message: " + raw_message);
        e.printStackTrace();
        return null;
    }

}

From source file:DOMIC.EncodeJson.java

public EncodeJson(String JsonText) {

    JSONParser jsonParser = new JSONParser();

    try {// w ww  .  j a  v a2 s. c  om

        JSONObject jsonObject = (JSONObject) jsonParser.parse(JsonText);

        JSONArray test = (JSONArray) jsonObject.get("test");

        for (int i = 0; i < test.size(); i++) {

            JSONArray questionBlock;
            this.questionBlocks.add(new QuestionBlock());
            questionBlock = (JSONArray) test.get(i);

            for (int j = 0; j < questionBlock.size(); j++) {

                HashMap questions = (HashMap) questionBlock.get(j);

                if (questions.get("-oa") != null) {

                    this.questionBlocks.get(i).questions.add(new Question((String) questions.get("-qu")));
                    JSONArray answerList = null;
                    answerList = (JSONArray) questions.get("-oa");

                    this.questionBlocks.get(i).questions.get(j).addAnswer(true, (String) answerList.get(0));

                }
                if (questions.get("-sa") != null) {

                    this.questionBlocks.get(i).questions.add(new Question((String) questions.get("-qu")));
                    JSONArray answerList = null;
                    answerList = (JSONArray) questions.get("-sa");
                    for (int k = 0; k < answerList.size(); k++) {
                        this.questionBlocks.get(i).questions.get(j).addAnswer(true, (String) answerList.get(k));
                    }

                }

                if (questions.get("-ma") != null) {

                    this.questionBlocks.get(i).questions.add(new Question((String) questions.get("-qu")));
                    JSONArray answerList = null;

                    answerList = (JSONArray) questions.get("-ma");
                    JSONArray trueAnswer = (JSONArray) answerList.get(0);
                    JSONArray falseAnswer = (JSONArray) answerList.get(1);

                    for (int k = 0; k < trueAnswer.size(); k++) {
                        this.questionBlocks.get(i).questions.get(j).addAnswer(true, (String) trueAnswer.get(k));

                    }
                    for (int k = 0; k < falseAnswer.size(); k++) {
                        this.questionBlocks.get(i).questions.get(j).addAnswer(false,
                                (String) falseAnswer.get(k));

                    }

                }

            }

        }

        System.out.println("");

    } catch (ParseException e) {
        e.printStackTrace();
    }

}

From source file:GraphController.java

@RequestMapping("/graphs")
public @ResponseBody Graph graph(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);// www.  ja  va2  s . c  o m

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    JSONArray list = new JSONArray();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "graph.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostids", hostid);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    String loginResponse = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response
        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        //         System.out.println(array);
        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            JSONObject objret = new JSONObject();

            objret.put("graphId", tobj.get("graphid"));
            objret.put("graphName", tobj.get("name"));

            String type = (String) tobj.get("graphtype");

            if (type.equals("0")) {
                objret.put("graphType", "normal");
            } else if (type.equals("1")) {
                objret.put("graphType", "stacked");
            } else if (type.equals("2")) {
                objret.put("graphType", "pie");
            } else if (type.equals("3")) {
                objret.put("graphType", "exploded");
            }

            list.add(objret);

        }

        return new Graph(list);

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return new Graph(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:ca.fastenalcompany.servlet.ProductServlet.java

/**
 * Provides GET /products and GET /products?id={id}
 *
 * @param request servlet request//from  w w  w  .j  a 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
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    response.setContentType("application/json");
    Set<String> keySet = request.getParameterMap().keySet();
    String id = request.getParameter("id");
    if (!keySet.contains("id")) {
        response.getWriter().write(query(PropertyManager.getProperty("db_selectAll")).toString());
    } else if (!id.isEmpty()) {
        JSONArray products = query(PropertyManager.getProperty("db_select"), id);
        response.getWriter()
                .write(products.isEmpty() ? new JSONObject().toString() : products.get(0).toString());
    }
}

From source file:it.analysis.IssueJsonReportTest.java

@Test
public void precise_issue_location() throws IOException {
    ItUtils.restoreProfile(orchestrator, getClass().getResource(RESOURCE_PATH + "multiline.xml"));
    orchestrator.getServer().provisionProject("sample-multiline", "xoo-sample");
    orchestrator.getServer().associateProjectToQualityProfile("sample-multiline", "xoo", "multiline");

    File projectDir = ItUtils.projectDir("shared/xoo-precise-issues");
    SonarScanner runner = SonarScanner.create(projectDir, "sonar.analysis.mode", "issues", "sonar.verbose",
            "true", "sonar.report.export.path", "sonar-report.json");
    BuildResult result = orchestrator.executeBuild(runner);
    assertThat(ItUtils.countIssuesInJsonReport(result, true)).isEqualTo(2);

    JSONObject obj = ItUtils.getJSONReport(result);
    JSONArray issues = (JSONArray) obj.get("issues");

    JSONObject issue1 = (JSONObject) issues.get(0);
    JSONObject issue2 = (JSONObject) issues.get(1);

    assertThat(issue1.get("startLine")).isIn(6L);
    assertThat(issue1.get("line")).isIn(6L);
    assertThat(issue1.get("endLine")).isIn(6L);
    assertThat(issue1.get("startOffset")).isIn(27L);
    assertThat(issue1.get("endOffset")).isIn(32L);

    assertThat(issue2.get("startLine")).isIn(9L);
    assertThat(issue2.get("line")).isIn(9L);
    assertThat(issue2.get("endLine")).isIn(15L);
    assertThat(issue2.get("startOffset")).isIn(20L);
    assertThat(issue2.get("endOffset")).isIn(2L);

}

From source file:com.teozcommunity.teozfrank.duelme.util.UpdateChecker.java

/**
 * Query the API to find the latest approved file's details.
 *///from   www. j  a  va2  s .co m
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:de.mpg.imeji.presentation.servlet.autocompleter.java

/**
 * Parse a CoNE Vocabulary (read the title value)
 * /*from   w w  w .j a  v  a  2 s .c  o m*/
 * @param cone
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private String parseConeVocabulary(String cone) throws IOException {
    Object obj = JSONValue.parse(cone);
    JSONArray array = (JSONArray) obj;
    JSONArray result = new JSONArray();
    for (int i = 0; i < array.size(); ++i) {
        JSONObject parseObject = (JSONObject) array.get(i);
        JSONObject sendObject = new JSONObject();
        sendObject.put("label", parseObject.get("http_purl_org_dc_elements_1_1_title"));
        sendObject.put("value", parseObject.get("http_purl_org_dc_elements_1_1_title"));
        result.add(sendObject);
    }
    StringWriter out = new StringWriter();
    result.writeJSONString(out);
    return out.toString();
}

From source file:net.bashtech.geobot.JSONUtil.java

public static ArrayList<String> tmiChatters(String channel) {
    try {//w ww. j av  a  2 s . c  o m
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(
                BotManager.getRemoteContent("https://tmi.twitch.tv/group/user/" + channel + "/chatters"));

        JSONObject jsonObject = (JSONObject) obj;
        JSONObject chatters = (JSONObject) jsonObject.get("chatters");
        JSONArray viewers = (JSONArray) chatters.get("viewers");
        JSONArray moderators = (JSONArray) chatters.get("moderators");
        for (int i = 0; i < moderators.size(); i++) {
            viewers.add(moderators.get(i));
        }

        return viewers;

    } catch (Exception ex) {
        System.out.println("Failed to get chatters");
        return null;
    }
}

From source file:me.timothy.ddd.quests.QuestManager.java

@SuppressWarnings("unchecked")
public QuestManager(Player player, AchievementManager aManager, EntityManager entManager) {
    logger = LogManager.getLogger();
    entityManager = entManager;//  w ww  . ja  v a2  s. c o  m
    achievementManager = aManager;
    acceptedQuests = new ArrayList<>();
    completedQuests = new ArrayList<>();
    this.player = player;

    File questsFile = new File("quests.json");
    if (questsFile.exists()) {
        try (FileReader fr = new FileReader(new File("quests.json"))) {
            JSONObject jObj = (JSONObject) (new JSONParser().parse(fr));

            JSONArray questsArr = (JSONArray) jObj.get("current");
            for (int i = 0; i < questsArr.size(); i++) {
                JSONObject questObj = (JSONObject) questsArr.get(i);
                String classStr = (String) questObj.get("class");
                Class<?> cl = Class.forName(classStr);
                Quest quest = null;
                try {
                    quest = (Quest) cl.getMethod("fromObject", getClass(), JSONObject.class).invoke(null, this,
                            questObj);
                } catch (NoSuchMethodException nsme) {
                    quest = (Quest) cl.getConstructor(QuestManager.class).newInstance(this);
                }
                acceptedQuests.add(quest);
            }

            JSONArray complete = (JSONArray) jObj.get("complete");
            for (int i = 0; i < complete.size(); i++) {
                //               completedQuests.add((Class<? extends Quest>) Class.forName((String) complete.get(i)));
            }
        } catch (Exception e) {
            logger.catching(e);
        }
    }

    Runnable saveQuests = new Runnable() {

        @Override
        public void run() {
            if (!DrunkDuckDispatch.ddd.save)
                return;
            JSONObject jObj = new JSONObject();
            JSONArray questsArr = new JSONArray();
            for (Quest qu : acceptedQuests) {
                questsArr.add(qu.asObject());
            }
            jObj.put("current", questsArr);
            JSONArray completed = new JSONArray();
            for (Class<? extends Quest> cl : completedQuests) {
                completed.add(cl.getCanonicalName());
            }
            jObj.put("complete", completed);
            try (FileWriter fw = new FileWriter(new File("quests.json"))) {
                jObj.writeJSONString(fw);
            } catch (IOException ie) {

            }
        }

    };

    Runtime.getRuntime().addShutdownHook(new Thread(saveQuests));
}

From source file:eu.hansolo.accs.RestClient.java

private JSONObject getSpecificObject(final URIBuilder BUILDER) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpGet get = new HttpGet(BUILDER.build());

        CloseableHttpResponse response = httpClient.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            //throw new RuntimeException("Failed: HTTP error code: " + statusCode);
            return new JSONObject();
        }/*from w w  w .ja v  a2 s  . c  om*/

        String output = getFromResponse(response);
        JSONArray jsonArray = (JSONArray) JSONValue.parse(output);
        JSONObject jsonObject = jsonArray.size() > 0 ? (JSONObject) jsonArray.get(0) : new JSONObject();
        return jsonObject;
    } catch (URISyntaxException | IOException e) {
        return new JSONObject();
    }
}