Example usage for org.json.simple JSONObject toString

List of usage examples for org.json.simple JSONObject toString

Introduction

In this page you can find the example usage for org.json.simple JSONObject toString.

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:org.apache.hadoop.chukwa.hicc.Workspace.java

public String convertObjectsToWidgetList(JSONObject[] objArray) {
    JSONObject jsonObj = new JSONObject();
    JSONArray jsonArr = new JSONArray();
    for (int i = 0; i < objArray.length; i++) {
        jsonArr.add(objArray[i]);//  w w  w  .  j ava 2s . c  o m
    }
    try {
        jsonObj.put("detail", jsonArr);
    } catch (Exception e) {
        System.err.println("JSON Exception: " + e.getMessage());
    }
    for (int i = 0; i < objArray.length; i++) {
        try {
            String[] categoriesArray = objArray[i].get("categories").toString().split(",");
            hash = addToHash(hash, categoriesArray, objArray[i]);
        } catch (Exception e) {
            System.err.println("JSON Exception: " + e.getMessage());
        }
    }
    try {
        jsonObj.put("children", hash);
    } catch (Exception e) {
        System.err.println("JSON Exception: " + e.getMessage());
    }
    return jsonObj.toString();
}

From source file:org.apache.hadoop.mapreduce.approx.lib.input.SampleRecordReader.java

public boolean nextKeyValue1() throws IOException, InterruptedException {
    while (nextKeyValueOrg()) {
        String currentValue = ((Text) this.getCurrentValue()).toString();
        JSONObject jsonCurrentValue = null;
        try {/*from   www  .  java2 s  . c o m*/
            jsonCurrentValue = (JSONObject) parser.parse(currentValue);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //LOG.info(currentValue);
        String[] keys = this.split.getKeys(idx - 1).split(Pattern.quote("*+*"));
        for (String key : keys) {
            //*************************************************************************fields separator**********************
            String[] fields = key.split(Pattern.quote("+*+"));
            boolean containCurrentKey = true;

            for (int i = 0; i < fields.length; i++) {
                //LOG.info("filter:" + field);
                String[] jsonwhere = whereKeys[fields.length - 1 - i].split(Pattern.quote("="))[0]
                        .split(Pattern.quote("."));
                JSONObject jsonkey = jsonCurrentValue;
                String jsonvalue = "";
                boolean flag = true;
                for (int j = 0; j < jsonwhere.length; j++) {
                    flag = true;
                    if (jsonkey.containsKey(jsonwhere[j])) {
                        if (fields[i].equals("true")) {
                            continue;
                        }
                        if (jsonkey.get(jsonwhere[j]).getClass().getName().equals("java.lang.String")) {
                            jsonvalue = (String) jsonkey.get(jsonwhere[j]);
                            flag = false;
                        } else {
                            jsonkey = (JSONObject) jsonkey.get(jsonwhere[j]);
                        }
                    } else {
                        containCurrentKey = false;
                        break;
                    }
                }
                if (!containCurrentKey) {
                    break;
                }
                if (fields[i].equals("true")) {
                    continue;
                }
                if (flag) {
                    jsonvalue = jsonkey.toString();
                }
                if (!jsonvalue.toLowerCase().contains(fields[i].toLowerCase())) {
                    containCurrentKey = false;
                    break;
                }
            }
            if (containCurrentKey) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.apache.metron.alerts.adapters.KeywordsAlertAdapter.java

@Override
public Map<String, JSONObject> alert(JSONObject raw_message) {

    Map<String, JSONObject> alerts = new HashMap<String, JSONObject>();
    JSONObject content = (JSONObject) raw_message.get("message");

    JSONObject enrichment = null;/*from   w  w w .java 2  s  .c om*/
    if (raw_message.containsKey("enrichment"))
        enrichment = (JSONObject) raw_message.get("enrichment");

    for (String keyword : keywordList) {
        if (content.toString().contains(keyword)) {

            //check it doesn't have an "exception" keyword in it
            for (String exception : keywordExceptionList) {
                if (content.toString().contains(exception)) {
                    LOG.info("[Metron] KeywordAlertsAdapter: Omitting alert due to exclusion: " + exception);
                    return null;
                }
            }

            LOG.info("[Metron] KeywordAlertsAdapter: Found match for " + keyword);
            JSONObject alert = new JSONObject();

            String source = "unknown";
            String dest = "unknown";
            String host = "unknown";

            if (content.containsKey("ip_src_addr")) {
                source = content.get("ip_src_addr").toString();

                if (RangeChecker.checkRange(loaded_whitelist, source))
                    host = source;
            }

            if (content.containsKey("ip_dst_addr")) {
                dest = content.get("ip_dst_addr").toString();

                if (RangeChecker.checkRange(loaded_whitelist, dest))
                    host = dest;
            }

            alert.put("designated_host", host);
            alert.put("description", content.get("original_string").toString());
            alert.put("priority", "MED");

            String alert_id = generateAlertId(source, dest, 0);

            alert.put("alert_id", alert_id);
            alerts.put(alert_id, alert);

            alert.put("enrichment", enrichment);

            return alerts;
        }
    }

    return null;
}

From source file:org.apache.metron.dataloads.ThreatIntelLoader.java

public static void main(String[] args) {

    PropertiesConfiguration sourceConfig = null;
    ThreatIntelSource threatIntelSource = null;
    ArrayList<Put> putList = null;
    HTable table = null;/*from w w w  . ja  v a  2 s  . c  om*/
    Configuration hConf = null;

    CommandLine commandLine = parseCommandLine(args);
    File configFile = new File(commandLine.getOptionValue("configFile"));

    try {
        sourceConfig = new PropertiesConfiguration(configFile);
    } catch (org.apache.commons.configuration.ConfigurationException e) {
        LOG.error("Error in configuration file " + configFile);
        LOG.error(e);
        System.exit(-1);
    }

    try {
        threatIntelSource = (ThreatIntelSource) Class.forName(commandLine.getOptionValue("source"))
                .newInstance();
        threatIntelSource.initializeSource(sourceConfig);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOG.error("Error while trying to load class " + commandLine.getOptionValue("source"));
        LOG.error(e);
        System.exit(-1);
    }

    hConf = HBaseConfiguration.create();
    try {
        table = new HTable(hConf, commandLine.getOptionValue("table"));
    } catch (IOException e) {
        LOG.error("Exception when processing HBase config");
        LOG.error(e);
        System.exit(-1);
    }

    putList = new ArrayList<Put>();

    while (threatIntelSource.hasNext()) {

        JSONObject intel = threatIntelSource.next();

        /*
         * If any of the required fields from threatIntelSource are
         * missing, or contain invalid data, don't put it in HBase.
         */
        try {

            putList.add(putRequestFromIntel(intel));

            if (putList.size() == BULK_SIZE) {
                table.put(putList);
                putList.clear();
            }

        } catch (NullPointerException | ClassCastException e) {
            LOG.error("Exception while processing intel object");
            LOG.error(intel.toString());
            LOG.error(e);
        } catch (InterruptedIOException
                | org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException e) {
            LOG.error("Problem communicationg with HBase");
            LOG.error(e);
            System.exit(-1);
        } catch (IOException e) {
            LOG.error("Problem communicationg with HBase");
            LOG.error(e);
            System.exit(-1);
        }
    }

}

From source file:org.apache.metron.indexing.adapters.ESBaseBulkAdapter.java

public boolean doIndex() throws Exception {

    try {//from w ww  .  j  ava2  s  .c o m

        synchronized (bulk_set) {
            if (client == null)
                throw new Exception("client is null");

            BulkRequestBuilder bulkRequest = client.prepareBulk();

            Iterator<JSONObject> iterator = bulk_set.iterator();

            while (iterator.hasNext()) {
                JSONObject setElement = iterator.next();

                IndexRequestBuilder a = client.prepareIndex(_index_name, _document_name);
                a.setSource(setElement.toString());
                bulkRequest.add(a);

            }

            _LOG.trace("[Metron] Performing bulk load of size: " + bulkRequest.numberOfActions());

            BulkResponse resp = bulkRequest.execute().actionGet();
            _LOG.trace("[Metron] Received bulk response: " + resp.toString());
            bulk_set.clear();
        }

        return true;
    }

    catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.apache.metron.indexing.adapters.ESTimedRotatingAdapter.java

public boolean doIndex() throws Exception {

    try {//from   w  ww . j a  v  a  2  s  .  co  m

        synchronized (bulk_set) {
            if (client == null)
                throw new Exception("client is null");

            BulkRequestBuilder bulkRequest = client.prepareBulk();

            Iterator<JSONObject> iterator = bulk_set.iterator();

            String index_postfix = dateFormat.format(new Date());

            while (iterator.hasNext()) {
                JSONObject setElement = iterator.next();

                _LOG.trace("[Metron] Flushing to index: " + _index_name + "_" + index_postfix);

                IndexRequestBuilder a = client.prepareIndex(_index_name + "_" + index_postfix, _document_name);
                a.setSource(setElement.toString());
                bulkRequest.add(a);

            }

            _LOG.trace("[Metron] Performing bulk load of size: " + bulkRequest.numberOfActions());

            BulkResponse resp = bulkRequest.execute().actionGet();

            for (BulkItemResponse r : resp.getItems()) {
                r.getResponse();
                _LOG.trace("[Metron] ES SUCCESS MESSAGE: " + r.getFailureMessage());
            }

            bulk_set.clear();

            if (resp.hasFailures()) {
                _LOG.error("[Metron] Received bulk response error: " + resp.buildFailureMessage());

                for (BulkItemResponse r : resp.getItems()) {
                    r.getResponse();
                    _LOG.error("[Metron] ES FAILURE MESSAGE: " + r.getFailureMessage());
                }
            }

        }

        return true;
    }

    catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.apache.pirk.storm.KafkaStormIntegrationTest.java

private void loadTestData(KafkaProducer<String, String> producer) {
    for (JSONObject dataRecord : Inputs.createJSONDataElements()) {
        logger.info("Sending record to Kafka " + dataRecord.toString());
        producer.send(new ProducerRecord<>(topic, dataRecord.toString()));
    }// ww w. j  a  v  a2 s . com
}

From source file:org.clothocad.phagebook.adaptors.ws.PhagebookSocket.java

private JSONObject handleIncomingMessage(String message) {
    JSONObject messageObject = new JSONObject();
    JSONParser parser = new JSONParser();

    try {//from   w ww .  j a  v  a  2 s . c o m
        messageObject = (JSONObject) parser.parse(message);
    } catch (ParseException ex) {
        Logger.getLogger(PhagebookSocket.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("INCOMING MESSAGE Object" + messageObject.toString());
    JSONObject result = new JSONObject();
    result.put("channel", (String) messageObject.get("channel"));
    result.put("requestId", messageObject.get("requestId"));
    if (isValidMessage(messageObject)) {
        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        switch (getChannel((String) messageObject.get("channel"))) {
        case CREATE_STATUS: {
            Map createStatusMap = new HashMap();
            createStatusMap = (Map) messageObject.get("data");

            Map loginMap = new HashMap();
            loginMap.put("username", createStatusMap.get("username"));
            loginMap.put("credentials", createStatusMap.get("password"));

            clothoObject.login(loginMap);

            Map queryMap = new HashMap();
            queryMap.put("emailId", createStatusMap.get("username"));

            // This is where it accesses Clotho and updates status
            List<Person> person = ClothoAdapter.queryPerson(queryMap, clothoObject,
                    ClothoAdapter.QueryMode.EXACT);
            List<String> statuses = person.get(0).getStatuses();
            if (statuses == null) {
                statuses = new ArrayList<String>();
            }

            Status newStatus = new Status();
            newStatus.setText((String) createStatusMap.get("status"));
            newStatus.setUserId(person.get(0).getId());
            //String statusId = ClothoAdapter.createStatus(newStatus, clothoObject);

            statuses.add(ClothoAdapter.createStatus(newStatus, clothoObject));
            clothoObject.logout();
            person.get(0).setStatuses(statuses);
            ClothoAdapter.setPerson(person.get(0), clothoObject);

            System.out.println("person status  -------" + person.get(0).getStatuses());
            // Status updated

            result.put("data", "Status created successfully.");

            break;
        }
        case CHANGE_ORDERING_STATUS: {
            Map getOrderMap = new HashMap();
            getOrderMap = (Map) messageObject.get("data");

            //                    Map loginMap = new HashMap();
            //                    loginMap.put("username",getOrderMap.get("username"));
            //                    loginMap.put("credentials",getOrderMap.get("password"));
            //                  
            //                    Map loginResult = new HashMap();
            //                    loginResult = (Map)clothoObject.login(loginMap);

            System.out.println("in Phagebook Socket, right before get Order ");
            Order order = ClothoAdapter.getOrder(getOrderMap.get("id").toString(), clothoObject);

            System.out.println("Order id received :: " + order.getId());

            order.setStatus(OrderStatus.valueOf(getOrderMap.get("status").toString()));
            System.out.println("Changed the order status " + order.getStatus());
            ClothoAdapter.setOrder(order, clothoObject);

            System.out.println("order status -------" + order.getStatus());

            result.put("data", "Status created successfully.");

            break;
        }
        case CREATE_PROJECT_STATUS: {
            Map getProjectMap = new HashMap();
            getProjectMap = (Map) messageObject.get("data");

            //                    Map loginMap = new HashMap();
            //                    loginMap.put("username",getProjectMap.get("username"));
            //                    loginMap.put("credentials",getProjectMap.get("password"));
            //                    
            //                    Map loginResult = new HashMap();
            //                    loginResult = (Map)clothoObject.login(loginMap);
            //                    
            //                    Map queryMap = new HashMap();
            //                    queryMap.put("emailId",getProjectMap.get("username"));
            //                    
            //                    List<Person> person = ClothoAdapter.queryPerson(queryMap, clothoObject, ClothoAdapter.QueryMode.EXACT);
            //                    List<String> projectids = person.get(0).getProjects();

            Project project = ClothoAdapter.getProject(getProjectMap.get("id").toString(), clothoObject);

            List<String> statuses = new ArrayList<String>();
            statuses.add((String) getProjectMap.get("status"));

            project.setUpdates(statuses);

            ClothoAdapter.setProject(project, clothoObject);

            System.out.println("project status -------" + project.getUpdates());

            result.put("data", "Status created successfully.");

            break;

        }
        case GET_PROJECTS: {
            Map getProjectsMap = new HashMap();
            getProjectsMap = (Map) messageObject.get("data");

            Map loginMap = new HashMap();
            loginMap.put("username", getProjectsMap.get("username"));
            loginMap.put("credentials", getProjectsMap.get("password"));

            Map loginResult = new HashMap();
            loginResult = (Map) clothoObject.login(loginMap);

            Map queryMap = new HashMap();
            queryMap.put("emailId", getProjectsMap.get("username"));

            List<Person> person = ClothoAdapter.queryPerson(queryMap, clothoObject,
                    ClothoAdapter.QueryMode.EXACT);

            List<String> projectids = person.get(0).getProjects();
            System.out.println("Name  :: " + person.toString());
            System.out.println("Ids of the Project :: " + person.get(0).toString());
            System.out.println("Projects :: " + person.get(0).getProjects());
            //System.out.println("person.get(0).getProjects() --------- " + person.get(0).getProjects());

            int numberOfProjects = projectids.size();

            //System.out.println("number of projects ------------- "+ numberOfProjects);

            List<Map> allProjects = new ArrayList<Map>();
            for (int i = 0; i < numberOfProjects; i++) {
                Map projectsMap = new HashMap();

                Project project = new Project();
                project = ClothoAdapter.getProject(projectids.get(i), clothoObject);

                projectsMap.put("projectId", project.getId());
                projectsMap.put("projectName", project.getName());
                allProjects.add(projectsMap);
            }

            result.put("data", allProjects);

            break;
        }
        case GET_ORDERS: {
            Map getOrdersMap = new HashMap();
            getOrdersMap = (Map) messageObject.get("data");

            Map loginMap = new HashMap();
            loginMap.put("username", getOrdersMap.get("username"));
            loginMap.put("credentials", getOrdersMap.get("password"));

            Map loginResult = new HashMap();
            loginResult = (Map) clothoObject.login(loginMap);

            Map queryMap = new HashMap();
            queryMap.put("emailId", getOrdersMap.get("username"));

            List<Person> person = ClothoAdapter.queryPerson(queryMap, clothoObject,
                    ClothoAdapter.QueryMode.EXACT);

            List<String> orderids = person.get(0).getCreatedOrders();

            int numberOfOrders = orderids.size();

            List<Map> allOrders = new ArrayList<Map>();
            for (int i = 0; i < numberOfOrders; i++) {
                Map ordersMap = new HashMap();

                Order order = new Order();
                order = ClothoAdapter.getOrder(orderids.get(i), clothoObject);

                ordersMap.put("orderId", order.getId());
                ordersMap.put("orderName", order.getName());
                allOrders.add(ordersMap);
            }

            result.put("data", allOrders);

            break;
        }
        case GET_PROJECT: {
            Map getProjectMap = new HashMap();
            getProjectMap = (Map) messageObject.get("data");

            Map loginMap = new HashMap();
            loginMap.put("username", getProjectMap.get("username"));
            loginMap.put("credentials", getProjectMap.get("password"));

            Map loginResult = new HashMap();
            loginResult = (Map) clothoObject.login(loginMap);

            Project project = ClothoAdapter.getProject(getProjectMap.get("id").toString(), clothoObject);

            JSONObject JSONProject = new JSONObject();

            JSONProject.put("creatorId", project.getCreatorId());
            JSONProject.put("leadId", project.getLeadId());
            JSONProject.put("members", project.getMembers());
            JSONProject.put("notebooks", project.getNotebooks());
            JSONProject.put("affiliatedLabs", project.getAffiliatedLabs());
            JSONProject.put("name", project.getName());
            JSONProject.put("dateCreated", project.getDateCreated().toString());
            JSONProject.put("updates", project.getUpdates());
            JSONProject.put("budget", project.getBudget());
            JSONProject.put("grantId", project.getGrantId());
            JSONProject.put("description", project.getDescription());
            JSONProject.put("id", project.getId());

            result.put("data", JSONProject);

            break;
        }
        case GET_ORDER: {
            Map getOrderMap = new HashMap();
            getOrderMap = (Map) messageObject.get("data");

            Map loginMap = new HashMap();
            loginMap.put("username", getOrderMap.get("username"));
            loginMap.put("credentials", getOrderMap.get("password"));

            Map loginResult = new HashMap();
            loginResult = (Map) clothoObject.login(loginMap);
            Order order = ClothoAdapter.getOrder(getOrderMap.get("id").toString(), clothoObject);

            JSONObject JSONOrder = new JSONObject();

            JSONOrder.put("id", order.getId());
            JSONOrder.put("name", order.getName());
            JSONOrder.put("description", order.getDescription());
            JSONOrder.put("dateCreated", order.getDateCreated().toString());
            JSONOrder.put("createdById", order.getCreatedById());
            JSONOrder.put("products", order.getProducts().toString());
            JSONOrder.put("budget", order.getBudget().toString());
            JSONOrder.put("maxOrderSize", order.getMaxOrderSize().toString());
            JSONOrder.put("approvedById", order.getApprovedById());
            JSONOrder.put("receivedById", order.getReceivedByIds());
            JSONOrder.put("relatedProjects", order.getRelatedProjectId());
            JSONOrder.put("status", order.getStatus().toString());

            result.put("data", JSONOrder);

            break;
        }
        default:
            result.put("data", "Error...");
            break;
        }
        conn.closeConnection();
    }
    return result;
}

From source file:org.csml.tommo.sugar.analysis.CachedFile.java

@Override
public String toJSONString() {
    JSONObject obj = toJSONObject();
    return obj.toString();
}

From source file:org.disit.servicemap.api.ServiceMapApi.java

public void queryLocation(JspWriter out, RepositoryConnection con, String lat, String lng) throws Exception {
    JSONObject obj = queryLocation(con, lat, lng);
    if (obj != null)
        out.print(obj.toString());
    else/*from  w  ww  . j a v  a  2 s. co  m*/
        out.println("{}");
}