Example usage for org.json.simple JSONObject JSONObject

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

Introduction

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

Prototype

JSONObject

Source Link

Usage

From source file:edu.iu.incntre.flowscale.util.JSONConverter.java

/**
 * convert List<OFStatistics> to JSONArray
 * @param ofs/*from  www.j  ava 2  s  . co  m*/
 * @return JSONArray
 */
public static JSONArray toTableStat(List<OFStatistics> ofs) {

    JSONArray jsonArray = new JSONArray();
    for (OFStatistics ofst : ofs) {

        OFTableStatistics st = (OFTableStatistics) ofst;
        // st.getPortNumber() st.getReceiveBytes();

        FlowscaleController.logger.debug("Maximum Entries {} and and Table id {}", st.getMaximumEntries(),
                st.getTableId());
        FlowscaleController.logger.debug("Name {} and and Table length {}", st.getName(), st.getLength());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("match_count", st.getMatchedCount());
        jsonObject.put("maximum_entries", st.getMaximumEntries());
        jsonObject.put("name", st.getName());
        jsonObject.put("table_id", st.getTableId());
        jsonObject.put("active_count", st.getActiveCount());

        jsonArray.add(jsonObject);

    }

    return jsonArray;

}

From source file:compare.handler.get.MetadataHandler.java

/**
 * Save the version1 metadata item to the METADATA database
 * @param jObj1 the object retrieved from the metadata database or null
 * @param conn the database connection//from  ww  w  .j a v a  2s  .  c  om
 * @throws CompareException if database save failed
 */
protected void saveToMetadata(JSONObject jObj1, Connection conn) throws CompareException {
    try {
        if (!saved && metadataValue != null && metadataValue.length() > 0) {
            if (jObj1 == null)
                jObj1 = new JSONObject();
            // update metadata for next time
            jObj1.put(metadataKey, metadataValue);
            if (jObj1.containsKey(JSONKeys._ID))
                jObj1.remove(JSONKeys._ID);
            conn.putToDb(Database.METADATA, docid, jObj1.toJSONString());
        }
    } catch (Exception e) {
        throw new CompareException(e);
    }
}

From source file:JavaCloud.Cloud.java

public ArrayList<Token> tokenList() throws CoreException {
    JSONObject object = new JSONObject();
    object.put("login", login);
    object.put("pw_hash", Utils.calcHash(password, seed));

    JSONArray jsontokens = (JSONArray) Utils.request(address, "/user/token/get_list/", object);

    ArrayList<Token> tokens = new ArrayList<Token>();
    for (int i = 0; i < jsontokens.size(); i++) {
        tokens.add(new Token(address, login, password, seed, (JSONObject) jsontokens.get(i)));
    }/*from w ww .  ja v a  2 s  .c o m*/

    return tokens;
}

From source file:at.yawk.selenium.resourcepack.McMeta.java

public JSONObject getRoot() throws McMetaException {
    if (rootObject == null) {
        if (file.exists()) {
            JSONParser parser = new JSONParser();
            try (InputStream i = file.getInput()) {
                rootObject = (JSONObject) parser.parse(new InputStreamReader(i));
            } catch (ParseException | IOException e) {
                throw new McMetaException(e);
            }//w ww .  ja v  a  2 s . c  o m
        } else {
            rootObject = new JSONObject();
        }
    }
    return rootObject;
}

From source file:modelo.ProcesoVertimientosManagers.Visitas.java

public JSONArray getVisitasPorProceso(String filaInicio, String filaFin, String tipoVisita, String fechaInicial,
        String fechaFinal, String codigoProceso, String estadoVisita, String contrato, String nit,
        String razonSocial, String motivoVisita) throws SQLException {

    JSONArray jsonArray = new JSONArray();
    JSONArray jsonArreglo = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    ResultSet rset;//w w w  .  jav a  2s .  com

    SeleccionarVisitas select = new SeleccionarVisitas(filaInicio, filaFin, tipoVisita, fechaInicial,
            fechaFinal, codigoProceso, estadoVisita, contrato, nit, razonSocial, motivoVisita);

    rset = select.getVisitas();

    while (rset.next()) {

        jsonObject.put("codigo", rset.getString("CODIGO"));
        jsonObject.put("nombre", rset.getString("NOMBRES"));
        jsonObject.put("apellidos", rset.getString("APELLIDOS"));
        jsonObject.put("fecha_visita", rset.getString("FECHA_VISITA"));
        jsonObject.put("motivo", rset.getString("MOVITO"));
        jsonObject.put("tipovisita", rset.getString("TIPOVISITA"));
        jsonObject.put("estado", rset.getString("ESTADO"));
        jsonObject.put("total", rset.getString("total_rows"));
        jsonObject.put("resultado", rset.getString("Resultado"));
        jsonObject.put("contrato", rset.getString("CONTRATO"));
        jsonObject.put("razon_social", rset.getString("RAZON_SOCIAL"));
        jsonObject.put("codigoProceso", rset.getString("CODPROCESO"));
        jsonObject.put("tecnicoVisito", rset.getString("TECNICO_VISITO"));

        jsonArray.add(jsonObject.clone());

    }

    jsonArreglo.add(jsonArray);

    //Se cierra el ResultSet
    select.desconectar();

    return jsonArreglo;

}

From source file:GenericResource.java

@GET
@Path("login/{cal}")
public String login(@PathParam("cal") String sth) {
    JSONObject array = new JSONObject();
    String time = null;/* www .  j  av a 2 s. co m*/
    String time2 = null;
    String[] tokens = sth.split(",");
    String username = tokens[0];
    String password = tokens[1];
    try {
        Class.forName("com.mysql.jdbc.Driver");
        String unicode = "?useUnicode=yes&characterEncoding=UTF-8";

        java.sql.Connection connection = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/finalproject" + unicode, "root", "");
        Statement statement = connection.createStatement();

        String x = "SELECT username,password from finalproject where username= '" + username
                + "' and password = '" + password + "'";

        ResultSet select = statement.executeQuery(x);
        while (select.next()) {
            array.put("status", "success");

        }

    } catch (ClassNotFoundException | SQLException exs) {

    }
    return array + "";
}

From source file:com.yottaa.newrelic.PostJob.java

/**
 *
 *//*  w  w  w.  j av a2  s  . c o m*/
public void postJobMethod() {

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

    logger.info("Posting Yottaa metrics to New Relic @ " + dateFormat.format(System.currentTimeMillis()));

    ResourceBundle bundle = ResourceBundle.getBundle("yottaa");
    YottaaHttpClientPublic yottaaHttpClientPublic = new YottaaHttpClientPublic(
            bundle.getString("yottaaAPIKey"));

    YottaaHttpClientPartner yottaaHttpClientPartner = new YottaaHttpClientPartner(false);

    // Prepare JSON data that will be posted to New Relic
    JSONObject jsonData = new JSONObject();

    JSONObject agentData = new JSONObject();
    agentData.put("host", "apps.yottaa.com");
    agentData.put("pid", 0);
    agentData.put("version", "1.0.0");

    jsonData.put("agent", agentData);

    JSONArray components = new JSONArray();

    JSONArray sites = yottaaHttpClientPartner.getAccountSites(bundle.getString("yottaaUserId"));

    logger.info("Total number of sites is " + sites.size() + ".");

    for (int i = 0, len = sites.size(); i < len; i++) {
        JSONObject siteObj = (JSONObject) sites.get(i);
        String host = (String) siteObj.get("host");

        logger.info("Retrieve last sample for host " + host + "(" + i + " of " + len + ").");

        JSONObject lastSampleMetrics = yottaaHttpClientPublic.getLastSample(host);

        JSONObject yottaaMetricsObj = new JSONObject();
        yottaaMetricsObj.put("guid", "com.yottaa.Yottaa");
        yottaaMetricsObj.put("duration", 60);
        //yottaaMetricsObj.put("name", host);
        yottaaMetricsObj.put("name", (String) lastSampleMetrics.get("name"));

        JSONObject yottaaMetricsData = new JSONObject();

        // Http Metrics
        if (lastSampleMetrics.get("http_metrics") != null) {
            JSONObject httpMetrics = (JSONObject) lastSampleMetrics.get("http_metrics");

            JSONObject httpMetricsFirstByte = (JSONObject) httpMetrics.get("first_byte");
            JSONObject httpMetricsWait = (JSONObject) httpMetrics.get("wait");
            JSONObject httpMetricsDNS = (JSONObject) httpMetrics.get("dns");
            JSONObject httpMetricsConnect = (JSONObject) httpMetrics.get("connect");

            yottaaMetricsData.put("Component/Http Metrics/Time To First Byte[sec]",
                    Double.parseDouble(httpMetricsFirstByte.get("average").toString()));
            yottaaMetricsData.put("Component/Http Metrics/Waiting Time[sec]",
                    Double.parseDouble(httpMetricsWait.get("average").toString()));
            yottaaMetricsData.put("Component/Http Metrics/DNS Time[sec]",
                    Double.parseDouble(httpMetricsDNS.get("average").toString()));
            yottaaMetricsData.put("Component/Http Metrics/Connection Time[sec]",
                    Double.parseDouble(httpMetricsConnect.get("average").toString()));
        }

        // Issue Metrics
        if (lastSampleMetrics.get("issue_metrics") != null) {
            JSONObject issueMetrics = (JSONObject) lastSampleMetrics.get("issue_metrics");

            yottaaMetricsData.put("Component/Issue Metrics/Critical Error Count[times]",
                    Integer.parseInt(issueMetrics.get("critical_error_count").toString()));
            yottaaMetricsData.put("Component/Issue Metrics/Error Count[times]",
                    Integer.parseInt(issueMetrics.get("error_count").toString()));
            yottaaMetricsData.put("Component/Issue Metrics/Info Count[times]",
                    Integer.parseInt(issueMetrics.get("info_count").toString()));
            yottaaMetricsData.put("Component/Issue Metrics/Warning Count[times]",
                    Integer.parseInt(issueMetrics.get("warning_count").toString()));
        }

        //Webpage Metrics
        if (lastSampleMetrics.get("webpage_metrics") != null) {
            JSONObject webpageMetrics = (JSONObject) lastSampleMetrics.get("webpage_metrics");
            JSONObject webpageMetricsTimeToRender = (JSONObject) webpageMetrics.get("time_to_render");
            JSONObject webpageMetricsTimeToDisplay = (JSONObject) webpageMetrics.get("time_to_display");
            JSONObject webpageMetricsTimeToInteract = (JSONObject) webpageMetrics.get("time_to_interact");

            yottaaMetricsData.put("Component/Webpage Metrics/Time To Render[sec]",
                    Double.parseDouble(webpageMetricsTimeToRender.get("average").toString()));
            yottaaMetricsData.put("Component/Webpage Metrics/Time To Display[sec]",
                    Double.parseDouble(webpageMetricsTimeToDisplay.get("average").toString()));
            yottaaMetricsData.put("Component/Webpage Metrics/Time To Interact[sec]",
                    Double.parseDouble(webpageMetricsTimeToInteract.get("average").toString()));
        }
        yottaaMetricsObj.put("metrics", yottaaMetricsData);

        components.add(yottaaMetricsObj);

        logger.info("Finished Retrieve last sample for host " + host + "(" + i + " of " + len + ").");
    }

    jsonData.put("components", components);

    logger.info("Posted Yottaa Metrics :" + jsonData);

    this.newrelicPost(null, bundle.getString("newrelicLicenseKey"), jsonData);

}

From source file:functionnality.LikerLineST2.java

public LineStatus rateLigne(String login, String value) {
    CouchDBWebRequest couchDB = new CouchDBWebRequest();
    message = "Consultation";
    JSONObject response;/*from w w  w.j a  va2 s  . co  m*/
    couchDB.addPath("/id_ligne_" + lineS.getIdentifiant());
    response = couchDB.parseResultJSON(couchDB.requestWithGet());
    //Requete des valeurs d'une ligne

    if (response.get("error") != null) {
        createTable(lineS.getIdentifiant());
        response = couchDB.parseResultJSON(couchDB.requestWithGet());
    }

    if (response.get("Voted") == null) {
        response.put("Voted", new JSONArray());
    }

    //((JSONObject)((JSONArray)response.get("Voted")).get(0)).get("login")
    int i = 0;
    boolean trouver = false;
    while (i < ((JSONArray) response.get("Voted")).size() && !trouver) {
        if (((JSONObject) ((JSONArray) response.get("Voted")).get(i)).get("login").equals(login)) {
            trouver = true;
        }
        i++;
    }
    if (trouver) {
        message = "You have already voted";
    } else {
        try {
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("login", new String(login.getBytes("ISO-8859-1"), Charset.forName("UTF-8")));
            jsonObj.put("value", value);
            if (value.equals("like")) {
                ((JSONObject) response).put("like", (long) response.get("like") + 1);
                message = "You have voted like with " + login;
            } else {
                ((JSONObject) response).put("unlike", (long) response.get("unlike") + 1);
                message = "You have voted unlike with " + login;
            }
            ((JSONArray) response.get("Voted")).add(jsonObj);
            couchDB.requestWithPut(response.toString());

        } catch (UnsupportedEncodingException ex) {
            return null;
        }
    }
    lineS.setLike(Integer.parseInt(("" + response.get("like"))));
    lineS.setUnlike(Integer.parseInt(("" + response.get("unlike"))));
    return lineS;
}

From source file:com.sesnu.orion.web.service.EstimatorService.java

public Estimate totalEstimate(OrderView order, Payment pay, Bid bid, Item item) {
    Estimate est = null;// ww w . j  a va2 s . com
    JSONObject pd = new JSONObject();
    double total = 0;

    // legalization
    est = legalization(order, pay);
    total += est.getValue();
    pd.put("Shipping Agency", addTotal(est));

    // license
    est = license(order);
    total += est.getValue();
    pd.put("License", addTotal(est));

    // customs
    est = customs(bid.getTotalBid(), bid.getCurrency(), item);
    total += est.getValue();
    pd.put("Customs", addTotal(est));

    // bromangol
    est = bromangol(order);
    total += est.getValue();
    pd.put("Bromangol", addTotal(est));

    // transport
    est = transport(order);
    total += est.getValue();
    pd.put("Transport", addTotal(est));

    // terminal

    est = terminal(order, bid.getTotalBid());
    pd.put("Terminal", addTotal(est));
    total += est.getValue();

    // port
    est = port(order);
    total += est.getValue();
    pd.put("Port", addTotal(est));

    // certificateOfQuality
    est = certificateOfQuality();
    total += est.getValue();
    pd.put("Certificate Of Quality", addTotal(est));

    // certificateOfHealth
    est = certificateOfHealth();
    total += est.getValue();
    pd.put("Agriculture Phyto.", addTotal(est));

    // phytosanitary
    est = phytosanitary();
    total += est.getValue();
    pd.put("Phytosanitary", addTotal(est));

    // forwardingAgent
    est = forwardingAgent(bid);
    total += est.getValue();
    pd.put("Forwarding Agent", addTotal(est));

    Exchange cur = exchangeDao.get("Other", "Other", "USD", "AOA");
    if (cur == null) {
        cur = exchangeDao.get("Customs", "Customs", "USD", "AOA");
        if (cur == null) {
            return null;
        }
    }

    JSONObject summary = new JSONObject();
    double totalInvAmount = bid.getTotalBid() * cur.getRate();
    summary.put("TotalCIFUSD", bid.getTotalBid());
    summary.put("TotalInvoiceAmount", totalInvAmount);
    summary.put("TotalFees", total);
    summary.put("TotalCost", total + totalInvAmount);
    summary.put("CostPerContainer", (total + totalInvAmount) / order.getContQnt());
    double costPerPack = (total + totalInvAmount) / order.getContQnt() / order.getPckPerCont();
    summary.put("CostPerPack", costPerPack);
    summary.put("pricePerPack", costPerPack * 1.12);
    summary.put("costCifRatio", (total + totalInvAmount) / totalInvAmount * 100);
    summary.put("pricePerPackUsd", costPerPack * 1.2 / cur.getRate());

    return new Estimate(total, pd, summary);
}

From source file:com.bigml.histogram.ArrayCategoricalTarget.java

@Override
@SuppressWarnings("unchecked")
protected void addJSON(JSONArray binJSON, DecimalFormat format) {
    JSONObject counts = new JSONObject();
    for (Entry<Object, Integer> categoryIndex : _indexMap.entrySet()) {
        Object category = categoryIndex.getKey();
        int index = categoryIndex.getValue();
        double count = _target[index];
        counts.put(category, Utils.roundNumber(count, format));
    }//  ww  w  .  j a  va  2 s  .  com
    binJSON.add(counts);
}