Example usage for org.json.simple JSONObject get

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Full form.//from  w w w .ja v  a 2 s  .  co  m
 */
public static void remove(String publisher, String pkgName, String version, boolean fromDisk, boolean fromDB)
        throws SQLException {
    List<RepoInfo> repos = getRepoUrls();
    for (RepoInfo inf : repos) {
        if (!inf.accessible)
            continue;
        String repo = inf.url;
        JSONObject repo_data = downloadMetadata(repo);
        JSONArray pkgs = (JSONArray) repo_data.get("packages");
        for (JSONObject obj : (List<JSONObject>) pkgs) {
            if (isPkg(publisher, pkgName, version, obj)) {
                if (fromDisk)
                    removeJar(jarName(obj));
                if (fromDB)
                    uninstallJar(jarName(obj));
                // automatically remove reverse-dependencies too, recursively.
                // Enhancement: optional function call param for this.
                for (String fullName : (List<String>) obj.get("rdepend")) {
                    for (RepoInfo depinf : repos) {
                        if (!depinf.accessible)
                            continue;
                        for (JSONObject depobj : (List<JSONObject>) downloadMetadata(inf.url).get("packages")) {
                            if (jarNameMatches(depobj, fullName)) {
                                remove(depobj.get("publisher").toString(), depobj.get("package").toString(),
                                        depobj.get("version").toString(), fromDisk, fromDB);
                                break;
                            }
                        }
                    }
                }
                return;
            }
        }
    }
}

From source file:com.storageroomapp.client.Collection.java

/**
 * Parses a String of json text and returns an Collection object.
 * It will correctly parse the Collection object if it is toplevel,
 * or also if nested in an 'collection' key-value pair.
 * //from  w  w  w  .  j a  va 2 s  .  c om
 * @param json the String with the json text
 * @return an Collection object, or null if the parsing failed
 */
static public Collection parseJson(Application parent, String json) {
    JSONObject collectionObj = (JSONObject) JSONValue.parse(json);
    if (collectionObj == null) {
        return null;
    }

    // unwrap the Collection object if it is a value with key 'collection;
    JSONObject collectionInnerObj = (JSONObject) collectionObj.get("collection");
    if (collectionInnerObj != null) {
        collectionObj = collectionInnerObj;
    }

    return parseJsonObject(parent, collectionObj);
}

From source file:controllers.IndexServlet.java

private static void Track(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) {
    String userAddress = request.getParameter("userAddress");
    String fileName = request.getParameter("fileName");

    String storagePath = DocumentManager.StoragePath(fileName, userAddress);
    String body = "";

    try {/*w  ww .j  ava  2 s  .  c  o  m*/
        Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
        body = scanner.hasNext() ? scanner.next() : "";
    } catch (Exception ex) {
        writer.write("get request.getInputStream error:" + ex.getMessage());
        return;
    }

    if (body.isEmpty()) {
        writer.write("empty request.getInputStream");
        return;
    }

    JSONParser parser = new JSONParser();
    JSONObject jsonObj;

    try {
        Object obj = parser.parse(body);
        jsonObj = (JSONObject) obj;
    } catch (Exception ex) {
        writer.write("JSONParser.parse error:" + ex.getMessage());
        return;
    }

    long status = (long) jsonObj.get("status");

    if (status == 2 || status == 3)//MustSave, Corrupted
    {
        String downloadUri = (String) jsonObj.get("url");

        int saved = 1;
        try {
            URL url = new URL(downloadUri);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            InputStream stream = connection.getInputStream();

            if (stream == null) {
                throw new Exception("Stream is null");
            }

            File savedFile = new File(storagePath);
            try (FileOutputStream out = new FileOutputStream(savedFile)) {
                int read;
                final byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }

                out.flush();
            }

            connection.disconnect();

        } catch (Exception ex) {
            saved = 0;
        }
    }

    writer.write("{\"error\":0}");
}

From source file:com.creapple.tms.mobiledriverconsole.utils.MDCUtils.java

/**
 * Get distance information between two GPS
 * @param originLat/*ww w .j  a va 2s. co  m*/
 * @param originLon
 * @param destLat
 * @param destLon
 * @return
 */
public static String[] getDistanceInfo(double originLat, double originLon, double destLat, double destLon) {

    String[] infos = new String[] { "0", "0" };

    String address = Constants.GOOGLE_DISTANCE_MATRIX_ADDRESS;
    address += originLat + "," + originLon;
    address += "&destinations=";
    address += destLat + "," + destLon;
    address += "&mode=driving&units=metric&language=en&key=";
    address += Constants.GOOGLE_DISTANCE_MATRIX_API_KEY;
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(address).build();
    Response response = null;
    String dist = null;
    try {
        response = client.newCall(request).execute();
        dist = response.body().string();
    } catch (IOException e) {
        return infos;
    }

    Log.d("@@@@@@", dist);
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = null;
    try {
        jsonObject = (JSONObject) jsonParser.parse(dist);
    } catch (ParseException e) {
        return infos;
    }

    // status check as well

    JSONArray rows = (JSONArray) jsonObject.get(Constants.GOOGLE_DISTANCE_MATRIX_ROWS);
    for (int i = 0; i < rows.size(); i++) {
        JSONObject obj = (JSONObject) rows.get(i);
        JSONArray elements = (JSONArray) obj.get(Constants.GOOGLE_DISTANCE_MATRIX_ELEMENTS);
        for (int j = 0; j < elements.size(); j++) {
            JSONObject datas = (JSONObject) elements.get(j);
            JSONObject distance = (JSONObject) datas.get(Constants.GOOGLE_DISTANCE_MATRIX_DISTANCE);
            JSONObject duration = (JSONObject) datas.get(Constants.GOOGLE_DISTANCE_MATRIX_DURATION);
            infos[0] = distance.get(Constants.GOOGLE_DISTANCE_MATRIX_VALUE) + "";
            infos[1] = duration.get(Constants.GOOGLE_DISTANCE_MATRIX_TEXT) + "";

        }

    }
    String status = jsonObject.get(Constants.GOOGLE_DISTANCE_MATRIX_STATUS).toString();
    //        Log.d("@@@@@@", status);
    if (!StringUtils.equalsIgnoreCase(Constants.GOOGLE_DISTANCE_MATRIX_OK, status)) {
        return infos;
    }
    return infos;
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java

/***
 * Used to parse, escape and enrich Kissmetircs Json records
 * //ww  w  . ja v  a2  s . c  om
 * @param rawJsonRow
 * @param fileNameInputToMapper
 * @return
 */
public static KeyRowWrapper parseJsonRowToValidJson(Text rawJsonRow, String fileNameInputToMapper,
        String filePath) {

    String jsonString = "";
    boolean wasOctalParsingNeeded = false;

    try {
        System.setProperty("file.encoding", "UTF-8");
        s = rawJsonRow.toString();
        Charset charSet = Charset.forName("UTF-8");
        byte[] encoded = s.getBytes(charSet);
        decodedStrRaw = new String(encoded, charSet);

        // Test new Apache Lang3
        // decodedStr = StringEscapeUtils.unescapeJava(decodedStr);

        //Replace any remaining Octal encoded Characters
        decodedStrParsed = replaceOctalUft8Char(decodedStrRaw);
        if (decodedStrParsed.compareTo(decodedStrRaw) == 0) {
            wasOctalParsingNeeded = false;
        } else {
            wasOctalParsingNeeded = true;
        }

        if (decodedStrParsed != null && decodedStrParsed != "") {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(decodedStrParsed);

            // get email and user_id
            if (jsonObject.get("_p2") != null) {
                p2 = jsonObject.get("_p2").toString().toLowerCase();
                if (p2.contains("@")) {
                    jsonObject.put("user_email", p2);
                    jsonObject.put("user_email_back", p2);
                } else if (p2 != null && p2.length() > 0) {
                    jsonObject.put("user_km_id", p2);
                }
            }
            // get email and user_id
            if (jsonObject.get("_p") != null) {
                p = jsonObject.get("_p").toString().toLowerCase();
                if (p.contains("@")) {
                    jsonObject.put("user_email", p);
                    jsonObject.put("user_email_back", p);
                } else if (p != null && p.length() > 0) {
                    jsonObject.put("user_km_id", p);
                }
            }

            // Add Event
            if (jsonObject.get("_n") != null) {
                event = jsonObject.get("_n").toString();
                if (event != null) {
                    jsonObject.put("event", event);
                }
            }

            // add unix timestamp and datetime
            long currentDateTime = System.currentTimeMillis();
            Date currentDate = new Date(currentDateTime);
            if (jsonObject.get("_t") == null) {
                return (new KeyRowWrapper(jsonString, null, TRACKING_COUNTER.INVALID_JSON_ROW,
                        TRACKING_COUNTER.INVALID_DATE));
            }
            long kmTimeDateMilliSeconds;
            long kmTimeDateMilliSecondsMobile;
            try {
                tTimestampValue = (String) jsonObject.get("_t").toString();

                //See if new record with server timestamp
                if (jsonObject.get("_server_timestamp") != null) {
                    serverTimestampValue = (String) jsonObject.get("_server_timestamp").toString();
                } else {
                    serverTimestampValue = "0";
                }

                //Deal with mobile timedate cases
                if (jsonObject.get("_c") != null) {
                    if (serverTimestampValue.equals("0")) {
                        timestampValueOutput = tTimestampValue;
                        kmTimeDateMilliSecondsMobile = 0;
                    } else {
                        timestampValueOutput = serverTimestampValue;
                        mobileTimestampValueOutput = tTimestampValue;
                        jsonObject.put("km_timestamp_mobile", mobileTimestampValueOutput);
                        kmTimeDateMilliSecondsMobile = Long.parseLong(mobileTimestampValueOutput) * 1000;
                    }
                } else {//Ignore server time
                        //TODO Need a way to resolve mobile identify events
                    serverTimestampValue = "0";
                    timestampValueOutput = tTimestampValue;
                    kmTimeDateMilliSecondsMobile = 0;
                }

                jsonObject.put("km_timestamp", timestampValueOutput);
                kmTimeDateMilliSeconds = Long.parseLong(timestampValueOutput) * 1000;
            } catch (Exception e) {
                return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.INVALID_JSON_ROW,
                        TRACKING_COUNTER.INVALID_DATE));
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(kmTimeDateMilliSeconds);
            String event_timedate = dateFormatter.format(calendar.getTime());
            jsonObject.put("event_timedate", event_timedate);

            if (kmTimeDateMilliSecondsMobile > 0) {
                calendar.setTimeInMillis(kmTimeDateMilliSecondsMobile);
                String event_timedate_mobile = dateFormatter.format(calendar.getTime());
                jsonObject.put("event_timedate_mobile", event_timedate_mobile);
            }

            // add Map Reduce json_filename
            jsonObject.put("filename", fileNameInputToMapper);
            jsonString = jsonObject.toString();

            //Add bucket path
            jsonObject.put("bucket", filePath);
            jsonString = jsonObject.toString();

            // TODO add the time the record was processed by Mapper:
            //jsonObject.put("capturedDate", capturedDate);
            //jsonString = jsonObject.toString();

            return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.VALID_JSON_ROW,
                    wasOctalParsingNeeded ? null : TRACKING_COUNTER.OCTAL_PARSING_NEEDED));

        }

    } catch (Exception e) {
        // System.err.println(e.getMessage());
        // e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        logger.error(errors.toString());

        logger.error("log - file " + fileNameInputToMapper);
        System.out.println("file " + fileNameInputToMapper);

        logger.error("log - row content: " + rawJsonRow.toString().replace("\t", ""));
        System.err.println("row content: " + rawJsonRow.toString().replace("\t", ""));

        System.err.println("Error skipping row");
        logger.error("Log - Error skipping row");
    }
    return null;
}

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

private static void doInfo(String cliwixServerUrl, Options options) {
    waitForServerReady(cliwixServerUrl, options);

    JSONObject json = getJson(cliwixServerUrl, "/services/info");
    JSONObject info = (JSONObject) json.get("info");

    console.println("Server info:");
    console.println("  Cliwix Version: " + info.get("cliwixVersion"));
    console.println("  Cliwix Workspace Directory: " + info.get("cliwixWorkspaceDirectory"));
    console.println("  Liferay Release: " + info.get("liferayRelease"));
}

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Full form./*  w  w w. ja  v  a  2s  .  c  o m*/
 */
public static void download(String publisher, String pkgName, String version, boolean install)
        throws SQLException {
    List<RepoInfo> repos = getRepoUrls();
    for (RepoInfo inf : repos) {
        if (!inf.accessible)
            continue;
        String repo = inf.url;
        // by default, we pick the package from the first repo we find it in.
        // Enhancement: supply repo url in function call.
        JSONObject repo_data = downloadMetadata(repo);
        JSONArray pkgs = (JSONArray) repo_data.get("packages");
        for (JSONObject obj : (List<JSONObject>) pkgs) {
            if (isPkg(publisher, pkgName, version, obj)) {
                String jar = jarName(obj);
                String url = repo;
                if (!url.endsWith("/"))
                    url += "/";
                if (obj.containsKey("url"))
                    url = obj.get("url").toString();
                else
                    url += jar;
                fetchJar(url, jar, obj.get("md5sum").toString());
                if (install)
                    installJar(jarName(obj));
                // automatically install dependencies, and the deps of deps,
                // recursively.
                // Enhancement: optional function call param for this.
                for (String fullName : (List<String>) obj.get("depend")) {
                    // we have to find which package it is without relying on
                    // splitting the string... and it could be in any repo!
                    // Yes this is very slow.
                    for (RepoInfo depinf : repos) {
                        if (!depinf.accessible)
                            continue;
                        for (JSONObject depobj : (List<JSONObject>) downloadMetadata(inf.url).get("packages")) {
                            if (jarNameMatches(depobj, fullName)) {
                                download(depobj.get("publisher").toString(), depobj.get("package").toString(),
                                        depobj.get("version").toString(), install);
                                break;
                            }
                        }
                    }
                }
                return;
            }
        }
    }
}

From source file:com.telefonica.iot.cygnus.utils.CommonUtils.java

/**
 * Gets the timestamp within a TimeInstant metadata, if exists.
 * @param metadata/*from   ww w.  j a va2  s .  c o  m*/
 * @return The timestamp within a TimeInstant metadata
 */
public static Long getTimeInstant(String metadata) {
    Long res = null;
    JSONParser parser = new JSONParser();
    JSONArray mds;

    try {
        mds = (JSONArray) parser.parse(metadata);
    } catch (ParseException e) {
        LOGGER.error("Error while parsing the metadaga. Details: " + e.getMessage());
        return null;
    } // try catch

    for (Object mdObject : mds) {
        JSONObject md = (JSONObject) mdObject;
        String mdName = (String) md.get("name");

        if (mdName.equals("TimeInstant")) {
            String mdValue = (String) md.get("value");

            if (isANumber(mdValue)) {
                res = new Long(mdValue);
            } else {
                DateTime dateTime;

                try {
                    // ISO 8601 without miliseconds
                    dateTime = FORMATTER1.parseDateTime(mdValue);
                } catch (Exception e1) {
                    LOGGER.debug(e1.getMessage());

                    try {
                        // ISO 8601 with miliseconds
                        dateTime = FORMATTER2.parseDateTime(mdValue);
                    } catch (Exception e2) {
                        LOGGER.debug(e2.getMessage());

                        try {
                            // ISO 8601 with microsencods
                            String mdValueTruncated = mdValue.substring(0, mdValue.length() - 4) + "Z";
                            dateTime = FORMATTER2.parseDateTime(mdValueTruncated);
                        } catch (Exception e3) {
                            LOGGER.debug(e3.getMessage());

                            try {
                                // SQL timestamp without miliseconds
                                dateTime = FORMATTER3.parseDateTime(mdValue);
                            } catch (Exception e4) {
                                LOGGER.debug(e4.getMessage());

                                try {
                                    // SQL timestamp with miliseconds
                                    dateTime = FORMATTER4.parseDateTime(mdValue);
                                } catch (Exception e5) {
                                    LOGGER.debug(e5.getMessage());

                                    try {
                                        // SQL timestamp with microseconds
                                        String mdValueTruncated = mdValue.substring(0, mdValue.length() - 3);
                                        dateTime = FORMATTER4.parseDateTime(mdValueTruncated);
                                    } catch (Exception e6) {
                                        LOGGER.debug(e6.getMessage());

                                        try {
                                            // ISO 8601 with offset (without milliseconds)
                                            dateTime = FORMATTER5.parseDateTime(mdValue);
                                        } catch (Exception e7) {
                                            LOGGER.debug(e7.getMessage());

                                            try {
                                                // ISO 8601 with offset (with milliseconds)
                                                Matcher matcher = FORMATTER6_PATTERN.matcher(mdValue);
                                                if (matcher.matches()) {
                                                    String mdValueTruncated = matcher.group(1) + "."
                                                            + matcher.group(2).substring(0, 3)
                                                            + matcher.group(3);
                                                    dateTime = FORMATTER6.parseDateTime(mdValueTruncated);
                                                } else {
                                                    LOGGER.debug("ISO8601 format does not match");
                                                    return null;
                                                } // if
                                            } catch (Exception e8) {
                                                LOGGER.debug(e8.getMessage());
                                                return null;
                                            } // try catch
                                        } // try catch
                                    } // try catch
                                } // try catch
                            } // try catch
                        } // try catch
                    } // try catch
                } // try catch

                GregorianCalendar cal = dateTime.toGregorianCalendar();
                res = cal.getTimeInMillis();
            } // if else

            break;
        } // if
    } // for

    return res;
}

From source file:com.cisco.dbds.utils.report.CustomReport.java

/**
 * Reportparsejson./*from w  w  w  .ja  v  a  2  s . co  m*/
 *
 * @return the string
 * @throws FileNotFoundException the file not found exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ParseException the parse exception
 * @throws AddressException the address exception
 */
public static String reportparsejson()
        throws FileNotFoundException, IOException, ParseException, AddressException {
    String failureReasonTable = "<table border style='width:100%'><tr style='background-color: rgb(70,116,209);'><colgroup><col span='1' style='width: 14%;'><col span='1' style='width: 40%;'><col span='1' style='width: 33%;'><col span='1' style='width: 13%;'></colgroup><th>Failed Test Case ID</th><th>Test Title</th><th>Failure Reason</th><th>Failure Category</th></tr>";
    String head = "<html>";
    head += "<head>";
    head += "<style>";
    head += "body{position:absolute;width:80%;height:100%;margin:0;padding:0}table,tbody{position:relative;width:100%;table-layout: auto}tr td,th{width:.5%;word-break:break-all;border:.5px solid black;} ";
    head += "</style>";
    head += "</head>";
    head += "<body border='2%'><table><tr><td style='background-color: rgb(170,187,204);'>";

    JSONParser parser = new JSONParser();
    int sno = 0;
    int pass = 0, fail = 0;
    int passed1 = 0, failed1 = 0;
    String headdetails = "<table><br><th style='background-color: rgb(25, 112, 193);'><center>Customized Automation Run Report</center></th><br></table><br><br>";
    String version = "";
    String bodydetailS = "<table> <tr style='background-color: rgb(70,116,209);'><th>#</th><th>Feature Name</th><th>TIMS ID</th><th>Test Type</th><th>Test Case Title</th><th>Status</th></tr>";
    String Total = "";
    Object obj = parser.parse(new FileReader("./target/reports/cucumber-report.json"));
    JSONArray msg = (JSONArray) obj;

    for (int i = 0; i < msg.size(); i++) {
        JSONObject jo = (JSONObject) msg.get(i);
        JSONArray msg1 = (JSONArray) jo.get("elements");
        String uniid = "";
        String nodeinfo = "";
        String featureFile = null;
        String timsId = null;
        String serial = null;
        String testType = null;
        String testTitle = null;
        String mid = null, mid1 = null;
        for (int j = 0; j < msg1.size(); j++) {

            JSONObject jo1 = (JSONObject) msg1.get(j);
            System.out.println("Id" + jo1.get("id"));
            if (jo1.get("id") != null) {

                JSONArray msg2 = (JSONArray) jo1.get("tags");

                String uniidstatus = "N";
                int pf = -1;
                System.out.println("satsize" + msg2.size());
                for (int j2 = 0; j2 < msg2.size(); j2++) {
                    // Version
                    JSONObject jo2 = (JSONObject) msg2.get(j2);
                    if ((jo2.get("name").toString().contains("NodeInfo"))) {
                        nodeinfo = "found";
                    }
                    // Test case details
                    if ((jo2.get("name").toString().contains("Ttv"))
                            || (jo2.get("name").toString().contains("TBD"))) {
                        String stype = "";
                        for (int typec = 0; typec < msg2.size(); typec++) {
                            JSONObject jotype = (JSONObject) msg2.get(typec);
                            if (jotype.get("name").toString().contains("Regression"))
                                stype = "Regression";
                            else if (jotype.get("name").toString().contains("Sanity"))
                                stype = "Sanity";

                        }
                        if (!uniid.trim().equals(jo2.get("name").toString().trim())) {

                            String feanmae[] = jo.get("uri").toString().split("/");
                            featureFile = feanmae[feanmae.length - 1];

                            serial = "" + (++sno);
                            timsId = jo2.get("name").toString();
                            testType = stype;
                            testTitle = jo1.get("name").toString();
                            mid = "<td><center>" + serial + "</center></td><td>" + featureFile
                                    + "</td><td><center>" + timsId.substring(1) + "</center></td><td><center>"
                                    + testType + "</center></td><td>" + testTitle + "</td>";
                            uniidstatus = "Y";

                            mid1 = "<td><center>" + timsId.substring(1) + "</center></td><td>" + testTitle
                                    + "</td>";

                        }

                        uniid = jo2.get("name").toString();

                    }
                }

                // Begin Version details
                if (nodeinfo.equals("found")) {
                    version = "<table border='2%' style='background-color: rgb(170,221,204);'>";
                    JSONArray msg5 = (JSONArray) jo1.get("steps");
                    System.out.println("Steps:" + msg5);
                    for (int j5 = 0; j5 < msg5.size(); j5++) {
                        JSONObject jo5 = (JSONObject) msg5.get(j5);
                        System.out.println(jo5.keySet());
                        JSONArray msg6 = (JSONArray) jo5.get("output");
                        System.out.println(msg6);
                        if (msg6 != null) {

                            for (int j6 = 0; j6 < msg6.size(); j6++) {
                                if (msg6.get(j6).toString().contains("cisco.conductor")) {
                                    System.out.println(msg6.get(j6));
                                    version += "<tr><td colspan=4><font style='color:rgb(0,102,0);'>"
                                            + msg6.get(j6).toString() + "</font></td></tr>";
                                } else {
                                    String rr[] = msg6.get(j6).toString().split(";");
                                    if (rr.length == 1) {
                                        version += "<tr><td colspan ='4'><center><b><font size=3 style='color:rgb(0,102,0);'>"
                                                + rr[0] + "</font></b></center></td></tr>";
                                    } else {
                                        version += "<tr border=''><td colspan=4 style='height:20px' /></tr><tr style='background-color: rgb(70,116,209);'><center>";

                                        for (int rr1 = 0; rr1 < rr.length; rr1++) {
                                            version += "<td colspan='" + (4 / rr.length) + "'>" + rr[rr1]
                                                    + "</td>";
                                        }
                                        version += "</center></tr>";
                                    }
                                }
                            }
                        }
                    }
                    version += "</table><br>";
                    System.out.println(version);
                }
                // End Version details

                JSONArray msg3 = (JSONArray) jo1.get("steps");
                //int pf = -1;
                for (int j3 = 0; j3 < msg3.size(); j3++) {
                    JSONObject jo3 = (JSONObject) msg3.get(j3);
                    JSONObject jo4 = (JSONObject) jo3.get("result");
                    System.out.println(jo4.get("status"));
                    if (jo4.get("status").equals("passed")) {
                        pf = 0;
                    } else {
                        pf = 1;
                        break;
                    }
                }

                if (uniidstatus.equals("Y")) {
                    if (pf == 0) {
                        bodydetailS += "<tr style='background-color: rgb(107,144,70);'>" + mid
                                + "<td><center>Passed</center></td></tr>";
                        pass++;
                    } else if (pf == 1) {
                        bodydetailS += "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                + "<td><center>Failed</center></td></tr>";
                        if (!failureReasonTable
                                .contains("<tr><td><center>" + mid1 + "</td><td></td><td></td></tr>"))
                            failureReasonTable += "<tr>" + mid1 + "<td></td><td></td></tr>";
                        fail++;
                    }
                } else if (mid != null) {
                    if (bodydetailS.contains(mid)) {
                        if (pf == 0) {/*
                                      if (bodydetailS.contains("<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>"))   
                                      {   
                                      bodydetailS=bodydetailS.replace( "<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>","<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>");
                                      //passed1--;
                                      }
                                      if (bodydetailS.contains("<tr style='background-color: rgb(216, 138, 138);'><center>"+mid+ "<td><center>Failed</center></td></tr>"))
                                      {
                                      bodydetailS=bodydetailS.replace( "<tr style='background-color: rgb(216, 138, 138);'><center>"+mid+ "<td><center>Failed</center></td></tr>","<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>");
                                      passed1++;
                                      failed1--;
                                              
                                      }*/
                        } else if (pf == 1) {
                            if (bodydetailS.contains("<tr style='background-color: rgb(107,144,70);'>" + mid
                                    + "<td><center>Passed</center></td></tr>")) {
                                failed1++;
                                passed1--;
                                bodydetailS = bodydetailS.replace(
                                        "<tr style='background-color: rgb(107,144,70);'>" + mid
                                                + "<td><center>Passed</center></td></tr>",
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>Failed</center></td></tr>");
                            }
                            if (bodydetailS
                                    .contains("<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                            + "<td><center>Failed</center></td></tr>")) {
                                bodydetailS = bodydetailS.replace(
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>Failed</center></td></tr>",
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>Failed</center></td></tr>");

                            }

                            if (!failureReasonTable
                                    .contains("<tr><td><center>" + mid1 + "</td><td></td><td></td></tr>"))
                                failureReasonTable += "<tr>" + mid1 + "<<td></td><td></td></tr>";
                        }

                    }
                    /*if (pf == 0 && uniidstatus.equals("Y")) {
                    bodydetailS += "<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>";
                    pass++;
                    } else if (pf == 1) {
                    bodydetailS += "<tr style='background-color: rgb(216, 138, 138);'><center>"+mid+ "<td><center>Failed</center></td></tr>";
                    failureReasonTable += "<tr><td><center>"
                       //   + timsId.substring(1) + "</center></td><td>"
                       + timsId
                          + testTitle + "</td><td></td><td></td></tr>";
                    fail++;
                    }*/
                }
            }
        }
    }

    Total = "<table><tr style='background-color: rgb(70,116,209);'><th>Total</th><td>Passed</th><th>Failed</th></tr>";
    Total += "<center><tr style='background-color: rgb(170,204,204);'><td>" + sno + "</td><td>"
            + (pass + passed1) + "(" + String.format("%.2f", ((pass + passed1) * 100.0F / sno)) + "%)</td><td>"
            + (fail + failed1) + "(" + String.format("%.2f", ((fail + failed1) * 100.0F / sno))
            + "%)</td></tr></center></table><br>";
    bodydetailS += "</center></table><br><br><br>";

    System.out.println(version);
    head += headdetails + Total + version + bodydetailS;
    if (fail > 0) {
        failureReasonTable += "</table>";
        // System.out.println(failureReasonTable);
        head += failureReasonTable;
    }
    head += "</td></tr></table></body></html>";

    return head;

}

From source file:com.sat.dbds.utils.report.CustomReport.java

/**
 * Reportparsejson./*from ww w . j av a  2s  .c  o m*/
 *
 * @return the string
 * @throws FileNotFoundException the file not found exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ParseException the parse exception
 * @throws AddressException the address exception
 */
public static String reportparsejson()
        throws FileNotFoundException, IOException, ParseException, AddressException {
    String failureReasonTable = "<table border style='width:100%'><tr style='background-color: rgb(70,116,209);'><colgroup><col span='1' style='width: 14%;'><col span='1' style='width: 40%;'><col span='1' style='width: 33%;'><col span='1' style='width: 13%;'></colgroup><th>Failed Test Case ID</th><th>Test Title</th><th>Failure Reason</th><th>Failure Category</th></tr>";
    String head = "<html>";
    head += "<head>";
    head += "<style>";
    head += "body{position:absolute;width:80%;height:100%;margin:0;padding:0}table,tbody{position:relative;width:100%;table-layout: auto}tr td,th{width:.5%;word-break:break-all;border:.5px solid black;} ";
    head += "</style>";
    head += "</head>";
    head += "<body border='2%'><table><tr><td style='background-color: rgb(170,187,204);'>";

    JSONParser parser = new JSONParser();
    int sno = 0;
    int pass = 0, fail = 0;
    int passed1 = 0, failed1 = 0;
    String headdetails = "<table><br><th style='background-color: rgb(25, 112, 193);'><center>Customized Automation Run Report</center></th><br></table><br><br>";
    String version = "";
    String bodydetailS = "<table> <tr style='background-color: rgb(70,116,209);'><th>#</th><th>Feature Name</th><th>TIMS ID</th><th>Test Type</th><th>Test Case Title</th><th>Status</th></tr>";
    String Total = "";
    Object obj = parser.parse(new FileReader("./target/reports/cucumber-report.json"));
    JSONArray msg = (JSONArray) obj;

    for (int i = 0; i < msg.size(); i++) {
        JSONObject jo = (JSONObject) msg.get(i);
        JSONArray msg1 = (JSONArray) jo.get("elements");
        String uniid = "";
        String nodeinfo = "";
        String featureFile = null;
        String timsId = null;
        String serial = null;
        String testType = null;
        String testTitle = null;
        String mid = null, mid1 = null;
        for (int j = 0; j < msg1.size(); j++) {

            JSONObject jo1 = (JSONObject) msg1.get(j);
            System.out.println("Id" + jo1.get("id"));
            if (jo1.get("id") != null) {

                JSONArray msg2 = (JSONArray) jo1.get("tags");

                String uniidstatus = "N";
                int pf = -1;
                System.out.println("satize" + msg2.size());
                for (int j2 = 0; j2 < msg2.size(); j2++) {
                    // Version
                    JSONObject jo2 = (JSONObject) msg2.get(j2);
                    if ((jo2.get("name").toString().contains("NodeInfo"))) {
                        nodeinfo = "found";
                    }
                    // Test case details
                    if ((jo2.get("name").toString().contains("Ttv"))
                            || (jo2.get("name").toString().contains("TBD"))) {
                        String stype = "";
                        for (int typec = 0; typec < msg2.size(); typec++) {
                            JSONObject jotype = (JSONObject) msg2.get(typec);
                            if (jotype.get("name").toString().contains("Regression"))
                                stype = "Regression";
                            else if (jotype.get("name").toString().contains("Sanity"))
                                stype = "Sanity";

                        }
                        if (!uniid.trim().equals(jo2.get("name").toString().trim())) {

                            String feanmae[] = jo.get("uri").toString().split("/");
                            featureFile = feanmae[feanmae.length - 1];

                            serial = "" + (++sno);
                            timsId = jo2.get("name").toString();
                            testType = stype;
                            testTitle = jo1.get("name").toString();
                            mid = "<td><center>" + serial + "</center></td><td>" + featureFile
                                    + "</td><td><center>" + timsId.substring(1) + "</center></td><td><center>"
                                    + testType + "</center></td><td>" + testTitle + "</td>";
                            uniidstatus = "Y";

                            mid1 = "<td><center>" + timsId.substring(1) + "</center></td><td>" + testTitle
                                    + "</td>";

                        }

                        uniid = jo2.get("name").toString();

                    }
                }

                // Begin Version details
                if (nodeinfo.equals("found")) {
                    version = "<table border='2%' style='background-color: rgb(170,221,204);'>";
                    JSONArray msg5 = (JSONArray) jo1.get("steps");
                    System.out.println("Steps:" + msg5);
                    for (int j5 = 0; j5 < msg5.size(); j5++) {
                        JSONObject jo5 = (JSONObject) msg5.get(j5);
                        System.out.println(jo5.keySet());
                        JSONArray msg6 = (JSONArray) jo5.get("output");
                        System.out.println(msg6);
                        if (msg6 != null) {

                            for (int j6 = 0; j6 < msg6.size(); j6++) {
                                if (msg6.get(j6).toString().contains("cisco.conductor")) {
                                    System.out.println(msg6.get(j6));
                                    version += "<tr><td colspan=4><font style='color:rgb(0,102,0);'>"
                                            + msg6.get(j6).toString() + "</font></td></tr>";
                                } else {
                                    String rr[] = msg6.get(j6).toString().split(";");
                                    if (rr.length == 1) {
                                        version += "<tr><td colspan ='4'><center><b><font size=3 style='color:rgb(0,102,0);'>"
                                                + rr[0] + "</font></b></center></td></tr>";
                                    } else {
                                        version += "<tr border=''><td colspan=4 style='height:20px' /></tr><tr style='background-color: rgb(70,116,209);'><center>";

                                        for (int rr1 = 0; rr1 < rr.length; rr1++) {
                                            version += "<td colspan='" + (4 / rr.length) + "'>" + rr[rr1]
                                                    + "</td>";
                                        }
                                        version += "</center></tr>";
                                    }
                                }
                            }
                        }
                    }
                    version += "</table><br>";
                    System.out.println(version);
                }
                // End Version details

                JSONArray msg3 = (JSONArray) jo1.get("steps");
                //int pf = -1;
                for (int j3 = 0; j3 < msg3.size(); j3++) {
                    JSONObject jo3 = (JSONObject) msg3.get(j3);
                    JSONObject jo4 = (JSONObject) jo3.get("result");
                    System.out.println(jo4.get("status"));
                    if (jo4.get("status").equals("passed")) {
                        pf = 0;
                    } else {
                        pf = 1;
                        break;
                    }
                }

                if (uniidstatus.equals("Y")) {
                    if (pf == 0) {
                        bodydetailS += "<tr style='background-color: rgb(107,144,70);'>" + mid
                                + "<td><center>Passed</center></td></tr>";
                        pass++;
                    } else if (pf == 1) {
                        bodydetailS += "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                + "<td><center>Failed</center></td></tr>";
                        if (!failureReasonTable
                                .contains("<tr><td><center>" + mid1 + "</td><td></td><td></td></tr>"))
                            failureReasonTable += "<tr>" + mid1 + "<td></td><td></td></tr>";
                        fail++;
                    }
                } else if (mid != null) {
                    if (bodydetailS.contains(mid)) {
                        if (pf == 0) {/*
                                      if (bodydetailS.contains("<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>"))   
                                      {   
                                      bodydetailS=bodydetailS.replace( "<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>","<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>");
                                      //passed1--;
                                      }
                                      if (bodydetailS.contains("<tr style='background-color: rgb(216, 138, 138);'><center>"+mid+ "<td><center>Failed</center></td></tr>"))
                                      {
                                      bodydetailS=bodydetailS.replace( "<tr style='background-color: rgb(216, 138, 138);'><center>"+mid+ "<td><center>Failed</center></td></tr>","<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>");
                                      passed1++;
                                      failed1--;
                                              
                                      }*/
                        } else if (pf == 1) {
                            if (bodydetailS.contains("<tr style='background-color: rgb(107,144,70);'>" + mid
                                    + "<td><center>Passed</center></td></tr>")) {
                                failed1++;
                                passed1--;
                                bodydetailS = bodydetailS.replace(
                                        "<tr style='background-color: rgb(107,144,70);'>" + mid
                                                + "<td><center>Passed</center></td></tr>",
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>Failed</center></td></tr>");
                            }
                            if (bodydetailS
                                    .contains("<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                            + "<td><center>Failed</center></td></tr>")) {
                                bodydetailS = bodydetailS.replace(
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>Failed</center></td></tr>",
                                        "<tr style='background-color: rgb(216, 138, 138);'><center>" + mid
                                                + "<td><center>Failed</center></td></tr>");

                            }

                            if (!failureReasonTable
                                    .contains("<tr><td><center>" + mid1 + "</td><td></td><td></td></tr>"))
                                failureReasonTable += "<tr>" + mid1 + "<<td></td><td></td></tr>";
                        }

                    }
                    /*if (pf == 0 && uniidstatus.equals("Y")) {
                    bodydetailS += "<tr style='background-color: rgb(107,144,70);'>"+mid+"<td><center>Passed</center></td></tr>";
                    pass++;
                    } else if (pf == 1) {
                    bodydetailS += "<tr style='background-color: rgb(216, 138, 138);'><center>"+mid+ "<td><center>Failed</center></td></tr>";
                    failureReasonTable += "<tr><td><center>"
                       //   + timsId.substring(1) + "</center></td><td>"
                       + timsId
                          + testTitle + "</td><td></td><td></td></tr>";
                    fail++;
                    }*/
                }
            }
        }
    }

    Total = "<table><tr style='background-color: rgb(70,116,209);'><th>Total</th><td>Passed</th><th>Failed</th></tr>";
    Total += "<center><tr style='background-color: rgb(170,204,204);'><td>" + sno + "</td><td>"
            + (pass + passed1) + "(" + String.format("%.2f", ((pass + passed1) * 100.0F / sno)) + "%)</td><td>"
            + (fail + failed1) + "(" + String.format("%.2f", ((fail + failed1) * 100.0F / sno))
            + "%)</td></tr></center></table><br>";
    bodydetailS += "</center></table><br><br><br>";

    System.out.println(version);
    head += headdetails + Total + version + bodydetailS;
    if (fail > 0) {
        failureReasonTable += "</table>";
        // System.out.println(failureReasonTable);
        head += failureReasonTable;
    }
    head += "</td></tr></table></body></html>";

    return head;

}