Example usage for com.liferay.portal.kernel.json JSONObject getDouble

List of usage examples for com.liferay.portal.kernel.json JSONObject getDouble

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.json JSONObject getDouble.

Prototype

public double getDouble(String key);

Source Link

Usage

From source file:com.beorn.paymentapi.model.ApiTransaction.java

License:Open Source License

public static ApiTransaction fromJSON(JSONObject jsonObject) {
    return new ApiTransaction(jsonObject.getLong("transactionId"), jsonObject.getLong("sellerId"),
            jsonObject.getDouble("amount"), jsonObject.getString("currencyCode"), jsonObject.getLong("status"));
}

From source file:com.fingence.slayer.service.impl.MyResultServiceImpl.java

License:Open Source License

public JSONArray getCollateralBreakdown(String portfolioIds) {

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    Connection conn = null;// w w  w.  ja v  a2  s.  co  m
    try {
        conn = DataAccess.getConnection();

        String[] tokens = { "[$PORTFOLIO_IDS$]", "[$FING_BOND_COLUMNS$]", "[$FING_BOND_TABLE$]",
                "[$FING_BOND_WHERE_CLAUSE$]" };
        String[] replacements = { portfolioIds, ",f.*, DATEDIFF(f.maturity_dt,now()) AS maturing_after",
                ",fing_Bond f", "and a.assetId = f.assetId" };

        String sql = StringUtil.replace(CustomSQLUtil.get(QUERY), tokens, replacements);

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        double totalMarketValue = getTotalMarketValue(portfolioIds);
        double totalValueOfBonds = 0.0;

        while (rs.next()) {
            String collatTyp = rs.getString("collat_typ");
            double currentMarketValue = rs.getDouble("currentMarketValue");
            totalValueOfBonds += currentMarketValue;

            JSONObject jsonObj = null;
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject _jsonObj = jsonArray.getJSONObject(i);
                    if (_jsonObj.getString("bucket").equalsIgnoreCase(collatTyp)) {
                        jsonObj = _jsonObj;
                        break;
                    }
                }
            }

            if (Validator.isNull(jsonObj)) {
                jsonObj = JSONFactoryUtil.createJSONObject();
                jsonObj.put("bucket", collatTyp);
                jsonObj.put("market_value", 0.0);
                jsonObj.put("bond_holdings_percent", 0.0);
                jsonObj.put("total_holdings_percent", 0.0);
                jsonArray.put(jsonObj);
            }

            jsonObj.put("market_value", jsonObj.getDouble("market_value") + currentMarketValue);
            jsonObj.put("total_holdings_percent",
                    jsonObj.getDouble("total_holdings_percent") + currentMarketValue * 100 / totalMarketValue);
        }

        rs.close();
        stmt.close();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            jsonObj.put("bond_holdings_percent", jsonObj.getDouble("market_value") * 100 / totalValueOfBonds);
        }

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DataAccess.cleanUp(conn);
    }

    return jsonArray;
}

From source file:com.fingence.slayer.service.impl.MyResultServiceImpl.java

License:Open Source License

public JSONArray getBondsMaturing(String portfolioIds) {

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    // initialization of JSONArray with default values
    for (int i = 0; i < bucketNames.length; i++) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
        jsonObject.put("bucket", bucketNames[i]);
        jsonObject.put("market_value", 0.0);
        jsonObject.put("bond_holdings_percent", 0.0);
        jsonObject.put("total_holdings_percent", 0.0);
        jsonArray.put(jsonObject);/*from  www.  j a v a 2  s  .  c  o m*/
    }

    Connection conn = null;
    try {
        conn = DataAccess.getConnection();

        String[] tokens = { "[$PORTFOLIO_IDS$]", "[$FING_BOND_COLUMNS$]", "[$FING_BOND_TABLE$]",
                "[$FING_BOND_WHERE_CLAUSE$]" };
        String[] replacements = { portfolioIds, ",f.*, round(mty_years_tdy * 360) AS maturing_after",
                ",fing_Bond f", "and a.assetId = f.assetId" };

        String sql = StringUtil.replace(CustomSQLUtil.get(QUERY), tokens, replacements);

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        double totalMarketValue = getTotalMarketValue(portfolioIds);
        double totalValueOfBonds = 0.0;

        while (rs.next()) {
            int maturingAfter = rs.getInt("maturing_after");
            double currentMarketValue = rs.getDouble("currentMarketValue");
            totalValueOfBonds += currentMarketValue;

            int index = 0;
            if (maturingAfter > 0 && maturingAfter <= 210) {
                index = 1;
            } else if (maturingAfter > 210 && maturingAfter <= 365) {
                index = 2;
            } else if (maturingAfter > 365 && maturingAfter <= 730) {
                index = 3;
            } else if (maturingAfter > 730 && maturingAfter <= 1825) {
                index = 4;
            } else if (maturingAfter > 1825 && maturingAfter <= 3650) {
                index = 5;
            } else if (maturingAfter > 3650) {
                index = 6;
            }

            JSONObject jsonObj = jsonArray.getJSONObject(index);

            jsonObj.put("market_value", jsonObj.getDouble("market_value") + currentMarketValue);
            jsonObj.put("total_holdings_percent",
                    jsonObj.getDouble("total_holdings_percent") + currentMarketValue * 100 / totalMarketValue);
        }

        rs.close();
        stmt.close();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            jsonObj.put("bond_holdings_percent", jsonObj.getDouble("market_value") * 100 / totalValueOfBonds);
        }

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DataAccess.cleanUp(conn);
    }

    return jsonArray;
}

From source file:com.fingence.slayer.service.impl.MyResultServiceImpl.java

License:Open Source License

public JSONArray getYldToMaturity(String portfolioIds) {

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    for (int i = 0; i < yldToMaturityRange.length; i++) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
        if (i <= 5) {
            jsonObject.put("yldToMaturityRange",
                    yldToMaturityRange[i][0] + StringPool.DASH + yldToMaturityRange[i][1]);
        } else {/*  w w  w  .j a v  a2s. c  o m*/
            jsonObject.put("yldToMaturityRange", yldToMaturityRange[i][0] + StringPool.PLUS);
        }
        for (int j = 0; j < durationRange.length; j++) {
            jsonObject.put((int) durationRange[j][0] + StringPool.DASH + (int) durationRange[j][1], 0.0d);
            jsonObject.put("index" + j, (i + StringPool.COLON + j));
        }
        jsonArray.put(jsonObject);
    }

    Connection conn = null;
    try {
        conn = DataAccess.getConnection();

        String[] tokens = { "[$PORTFOLIO_IDS$]", "[$FING_BOND_COLUMNS$]", "[$FING_BOND_TABLE$]",
                "[$FING_BOND_WHERE_CLAUSE$]" };
        String[] replacements = { portfolioIds, ",f.*", ",fing_Bond f", "and a.assetId = f.assetId" };

        String sql = StringUtil.replace(CustomSQLUtil.get(QUERY), tokens, replacements);

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        double totalValueOfBonds = 0.0;

        while (rs.next()) {
            double dur_mid = rs.getDouble("dur_mid");
            double yld_ytm_bid = rs.getDouble("yld_ytm_bid");

            double currentMarketValue = rs.getDouble("currentMarketValue");
            totalValueOfBonds += currentMarketValue;

            for (int i = 0; i < yldToMaturityRange.length; i++) {
                if (yld_ytm_bid > yldToMaturityRange[i][0] && yld_ytm_bid <= yldToMaturityRange[i][1]) {
                    JSONObject jsonObj = jsonArray.getJSONObject(i);
                    for (int j = 0; j < durationRange.length; j++) {
                        if (dur_mid > durationRange[j][0] && dur_mid <= durationRange[j][1]) {
                            String key = (int) durationRange[j][0] + StringPool.DASH
                                    + (int) durationRange[j][1];
                            jsonObj.put(key, jsonObj.getDouble(key) + currentMarketValue);
                        }
                    }
                }
            }
        }

        rs.close();
        stmt.close();

        for (int i = 0; i < yldToMaturityRange.length; i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            for (int j = 0; j < durationRange.length; j++) {
                String key = (int) durationRange[j][0] + StringPool.DASH + (int) durationRange[j][1];
                jsonObj.put(key, jsonObj.getDouble(key) * 100 / totalValueOfBonds);
            }
        }

        // append a summary row
        JSONObject summary = JSONFactoryUtil.createJSONObject();
        summary.put("summary", true);
        summary.put("yldToMaturityRange", "Total");
        for (int i = 0; i < yldToMaturityRange.length; i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            for (int j = 0; j < durationRange.length; j++) {
                String key = (int) durationRange[j][0] + StringPool.DASH + (int) durationRange[j][1];
                if (Double.isNaN(summary.getDouble(key))) {
                    summary.put(key, jsonObj.getDouble(key));
                } else {
                    summary.put(key, summary.getDouble(key) + jsonObj.getDouble(key));
                }
            }
        }

        jsonArray.put(summary);

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DataAccess.cleanUp(conn);
    }

    return jsonArray;
}

From source file:com.fingence.slayer.service.impl.MyResultServiceImpl.java

License:Open Source License

public JSONArray getCpnTypVsMtyTyp(String portfolioIds) {

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    List<String> cpnTypes = getDistinctValues("cpn_typ", portfolioIds);
    List<String> mtyTypes = getDistinctValues("mty_typ", portfolioIds);

    for (String cpnType : cpnTypes) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

        jsonObject.put("cpnType", cpnType);
        int i = 0;
        for (String mtyType : mtyTypes) {
            jsonObject.put(mtyType, 0.0d);
            jsonObject.put(cpnType + ++i, mtyType + StringPool.COLON + cpnType);

        }/* ww  w  .  ja va2s  . co m*/
        jsonObject.put("grandTotal", 0.0d);

        jsonArray.put(jsonObject);
    }

    Connection conn = null;
    try {
        conn = DataAccess.getConnection();

        String[] tokens = { "[$PORTFOLIO_IDS$]", "[$FING_BOND_COLUMNS$]", "[$FING_BOND_TABLE$]",
                "[$FING_BOND_WHERE_CLAUSE$]" };
        String[] replacements = { portfolioIds, ",f.*", ",fing_Bond f", "and a.assetId = f.assetId" };

        String sql = StringUtil.replace(CustomSQLUtil.get(QUERY), tokens, replacements);

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        double totalValueOfBonds = 0.0;

        while (rs.next()) {
            String cpn_typ = rs.getString("cpn_typ");
            String mty_typ = rs.getString("mty_typ");

            double currentMarketValue = rs.getDouble("currentMarketValue");
            totalValueOfBonds += currentMarketValue;

            for (int i = 0; i < cpnTypes.size(); i++) {
                if (cpn_typ.equalsIgnoreCase(cpnTypes.get(i))) {
                    JSONObject jsonObj = jsonArray.getJSONObject(i);
                    for (String mtyType : mtyTypes) {
                        if (mtyType.equalsIgnoreCase(mty_typ)) {
                            jsonObj.put(mtyType, jsonObj.getDouble(mtyType) + currentMarketValue);
                        }
                    }
                }
            }
        }

        rs.close();
        stmt.close();

        for (int i = 0; i < cpnTypes.size(); i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            for (String mtyType : mtyTypes) {
                jsonObj.put(mtyType, jsonObj.getDouble(mtyType) * 100 / totalValueOfBonds);
                if (Double.isNaN(jsonObj.getDouble("grandTotal"))) {
                    jsonObj.put("grandTotal", jsonObj.getDouble(mtyType));
                } else {
                    jsonObj.put("grandTotal", jsonObj.getDouble(mtyType) + jsonObj.getDouble("grandTotal"));
                }
            }
        }

        // append a summary row
        double grandTotal = 0.0d;
        JSONObject summary = JSONFactoryUtil.createJSONObject();
        summary.put("summary", true);
        summary.put("cpnType", "Grand Total");
        for (int i = 0; i < cpnTypes.size(); i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            for (String mtyType : mtyTypes) {
                if (Double.isNaN(summary.getDouble(mtyType))) {
                    summary.put(mtyType, jsonObj.getDouble(mtyType));
                } else {
                    summary.put(mtyType, summary.getDouble(mtyType) + jsonObj.getDouble(mtyType));
                    grandTotal += summary.getDouble(mtyType);
                }
            }
        }

        summary.put("grandTotal", grandTotal);
        jsonArray.put(summary);

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DataAccess.cleanUp(conn);
    }

    return jsonArray;
}

From source file:com.fingence.slayer.service.impl.MyResultServiceImpl.java

License:Open Source License

public JSONArray getBondsQuality(String portfolioIds) {

    String[] categories = { "Investment", "Non Investment", "Others" };

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    // initialization of JSONArray with default values
    for (int i = 0; i < categories.length; i++) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
        jsonObject.put("category", categories[i]);
        jsonObject.put("children", JSONFactoryUtil.createJSONArray());
        jsonArray.put(jsonObject);//from w ww.j a v  a 2s  .  c o  m
    }

    Connection conn = null;
    try {
        conn = DataAccess.getConnection();

        String[] tokens = { "[$PORTFOLIO_IDS$]", "[$FING_BOND_COLUMNS$]", "[$FING_BOND_TABLE$]",
                "[$FING_BOND_WHERE_CLAUSE$]" };
        String[] replacements = { portfolioIds, ",f.*", ",fing_Bond f", "and a.assetId = f.assetId" };

        String sql = StringUtil.replace(CustomSQLUtil.get(QUERY), tokens, replacements);

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        double totalMarketValue = getTotalMarketValue(portfolioIds);
        double totalValueOfBonds = 0.0;

        while (rs.next()) {
            double currentMarketValue = rs.getDouble("currentMarketValue");
            totalValueOfBonds += currentMarketValue;

            String spRating = rs.getString("rtg_sp");
            String moodyRating = rs.getString("rtg_moody");

            Rating rating = null;
            try {
                rating = ratingPersistence.fetchBySP_Moody(spRating, moodyRating);
            } catch (SystemException e) {
                e.printStackTrace();
            }

            // identify the object 
            int index = 2;
            String description = "No Rating Available";
            if (Validator.isNotNull(rating)) {
                String category = rating.getCategory();
                description = rating.getDescription();

                for (int i = 0; i < categories.length; i++) {
                    if (categories[i].equalsIgnoreCase(category)) {
                        index = i;
                    }
                }
            }

            JSONArray children = jsonArray.getJSONObject(index).getJSONArray("children");

            // identify the child within the parent
            JSONObject child = null;

            if (children.length() == 0) {
                child = JSONFactoryUtil.createJSONObject();
                child.put("bucket", description);
                child.put("market_value", 0.0);
                child.put("bond_holdings_percent", 0.0);
                child.put("total_holdings_percent", 0.0);
                children.put(child);
            }

            for (int i = 0; i < children.length(); i++) {
                child = children.getJSONObject(i);
                if (child.getString("bucket").equalsIgnoreCase(description)) {
                    child.put("market_value", child.getDouble("market_value") + currentMarketValue);
                    child.put("total_holdings_percent", child.getDouble("total_holdings_percent")
                            + currentMarketValue * 100 / totalMarketValue);
                }
            }
        }

        rs.close();
        stmt.close();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject parent = jsonArray.getJSONObject(i);
            JSONArray children = parent.getJSONArray("children");

            for (int j = 0; j < children.length(); j++) {
                JSONObject child = children.getJSONObject(j);
                child.put("bond_holdings_percent", child.getDouble("market_value") * 100 / totalValueOfBonds);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DataAccess.cleanUp(conn);
    }

    return jsonArray;
}

From source file:com.liferay.dynamic.data.mapping.internal.render.GeolocationDDMFormFieldValueRenderer.java

License:Open Source License

@Override
protected ValueAccessor getValueAcessor(Locale locale) {
    return new ValueAccessor(locale) {

        @Override/*from  ww  w.  j  a v  a2s .  c  o m*/
        public String get(DDMFormFieldValue ddmFormFieldValue) {
            Value value = ddmFormFieldValue.getValue();

            JSONObject jsonObject = createJSONObject(value.getString(locale));

            StringBundler sb = new StringBundler(7);

            sb.append(LanguageUtil.get(locale, "latitude"));
            sb.append(": ");

            double latitude = jsonObject.getDouble("latitude");

            NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);

            sb.append(numberFormat.format(latitude));

            sb.append(StringPool.COMMA_AND_SPACE);
            sb.append(LanguageUtil.get(locale, "longitude"));
            sb.append(": ");

            double longitude = jsonObject.getDouble("longitude");

            sb.append(numberFormat.format(longitude));

            return sb.toString();
        }

        protected JSONObject createJSONObject(String json) {
            try {
                return JSONFactoryUtil.createJSONObject(json);
            } catch (JSONException jsone) {
                throw new ValueAccessorException(jsone);
            }
        }

    };
}

From source file:com.liferay.dynamic.data.mapping.storage.impl.GeolocationFieldRenderer.java

License:Open Source License

protected String handleJSON(String value, Locale locale) {
    JSONObject jsonObject = null;

    try {/*from  ww w . ja v  a  2  s.co  m*/
        jsonObject = JSONFactoryUtil.createJSONObject(value);
    } catch (JSONException jsone) {
        if (_log.isDebugEnabled()) {
            _log.debug("Unable to parse JSON", jsone);
        }

        return StringPool.BLANK;
    }

    StringBundler sb = new StringBundler(7);

    sb.append(LanguageUtil.get(locale, "latitude"));
    sb.append(": ");

    double latitude = jsonObject.getDouble("latitude");

    NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);

    sb.append(numberFormat.format(latitude));

    sb.append(StringPool.COMMA_AND_SPACE);
    sb.append(LanguageUtil.get(locale, "longitude"));
    sb.append(": ");

    double longitude = jsonObject.getDouble("longitude");

    sb.append(numberFormat.format(longitude));

    return sb.toString();
}

From source file:com.liferay.events.global.mobile.service.impl.EventContactServiceImpl.java

License:Open Source License

private static String getJSONInterestsFromString(String interestStr, String existing, String source,
        Map<String, String> eventConfig) throws IOException, JSONException {

    String newStr = Utils.removeStopWords(interestStr);

    // remove newlines and other junk, make sure one space, lower case, etc
    newStr = newStr.replaceAll("[!\"#$%&'()*+,\\\\\\-./:;<=>?@\\[\\]^_`{|}~]", " ").replaceAll("\t", " ")
            .replaceAll(" {2,} ", " ").replaceAll("\n + $ ", "").replaceAll(" ^\n +", "")
            .replaceAll(" \n {2,}", " ").trim().toLowerCase();

    List<String> phrases = new ArrayList<String>();

    String weightStr = eventConfig.get("interest_weights");
    if (weightStr != null) {
        JSONArray weightArr = JSONFactoryUtil.createJSONArray(weightStr);
        int len = weightArr.length();
        for (int i = 0; i < len; i++) {
            String str = weightArr.getJSONObject(i).getString("word");
            phrases.add(str);//from w w w  .ja v a  2  s .co m
            newStr = newStr.replaceAll(str, "");
        }
    }

    List<String> words = new ArrayList<String>();

    words.addAll(Arrays.asList(newStr.split("\\s+")));
    //words.addAll(phrases);

    final Map<String, Integer> profileWordsMap = new TreeMap<String, Integer>() {
        @Override
        public Integer put(final String key, final Integer value) {
            if (containsKey(key)) {
                return super.put(key, get(key) + value);
            } else {
                return super.put(key, value);
            }
        }
    };

    for (String word : words) {
        if (word.length() < INTERESTS_MIN_WORD_LENGTH || word.length() >= INTERESTS_MAX_WORD_LENGTH) {
            continue;
        }
        profileWordsMap.put(word, 1);
    }

    // subtract one
    for (String phrase : phrases) {
        if (profileWordsMap.containsKey(phrase)) {

            int count = profileWordsMap.get(phrase);
            if (count <= 1) {
                profileWordsMap.remove(phrase);
            } else {
                profileWordsMap.put(phrase, -1);
            }
        }
    }

    JSONArray existArr = null;

    // put existing words in if any
    if (Validator.isNotNull(existing)) {
        existArr = JSONFactoryUtil.createJSONArray(existing);
    }

    JSONArray weightArr = JSONFactoryUtil.createJSONArray(eventConfig.get("interest_weights"));

    Map<String, Double> configuredWeights = new HashMap<String, Double>();
    for (int i = 0; i < weightArr.length(); i++) {
        JSONObject obj = weightArr.getJSONObject(i);
        configuredWeights.put(obj.getString("word"), obj.getDouble("weight"));
    }

    JSONArray arr = JSONFactoryUtil.createJSONArray();

    for (String s : profileWordsMap.keySet()) {
        JSONObject existingObj;
        Set<String> existingSrcs;

        if (Validator.isNotNull(existArr)
                && Validator.isNotNull((existingObj = getExistingWordRecord(s, existArr)))) {
            if (Validator.isNotNull(existingObj)) {
                existingSrcs = new HashSet<String>(
                        Arrays.asList(StringUtils.split(existingObj.getString("source"), StringPool.COMMA)));
                existingSrcs.add(source);
                JSONObject obj = JSONFactoryUtil.createJSONObject();
                obj.put("word", s);
                obj.put("source", StringUtils.join(existingSrcs, StringPool.COMMA));
                obj.put("count", profileWordsMap.get(s) + existingObj.getInt(s));
                obj.put("weight", existingObj.getDouble("weight"));
                arr.put(obj);
            }
        } else {
            JSONObject obj = JSONFactoryUtil.createJSONObject();
            obj.put("word", s);
            obj.put("source", source);
            obj.put("count", profileWordsMap.get(s));
            obj.put("weight", configuredWeights.containsKey(s) ? configuredWeights.get(s) : 1.0);
            arr.put(obj);
        }
    }

    // put existing words that didn't show up in the profile
    if (Validator.isNotNull(existArr)) {
        for (int i = 0; i < existArr.length(); i++) {
            JSONObject existingObj = existArr.getJSONObject(i);
            if (!profileWordsMap.containsKey(existingObj.getString("word"))) {
                arr.put(existingObj);
            }
        }
    }
    return arr.toString();
}

From source file:com.liferay.events.global.mobile.Utils.java

License:Open Source License

public static String getJSONLikenessDescription(EventContact me, EventContact targetContact)
        throws JSONException {

    JSONArray result = JSONFactoryUtil.createJSONArray();

    Map<String, Double> desires1 = getJSONWordWeightsFromString(me.getDesires());
    Map<String, Double> desires2 = getJSONWordWeightsFromString(targetContact.getDesires());
    Map<String, Double> expertise1 = getJSONWordWeightsFromString(me.getExpertise());
    Map<String, Double> expertise2 = getJSONWordWeightsFromString(targetContact.getExpertise());

    // how many of my desires do they have expertise in?
    Set<String> common1 = new HashSet<String>(desires1.keySet());
    common1.retainAll(expertise2.keySet());

    // how many of my expertises do they desire?
    Set<String> common2 = new HashSet<String>(desires2.keySet());
    common2.retainAll(expertise1.keySet());

    if (common1.size() > 0) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();

        List<String> myNeeds = new ArrayList<String>(common1);
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        args.put(StringUtils.join(myNeeds.size() > 5 ? myNeeds.subList(0, 5) : myNeeds,
                " " + StringPool.SLASH + " "));

        bit.put("key", "HAS_EXPERTISE_IN_MY_AREAS");
        bit.put("args", args);
        result.put(bit);// w  ww .  j  a v a 2 s. c  o  m
    }

    if (common2.size() > 0) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();

        List<String> myExpertise = new ArrayList<String>(common2);
        args.put(targetContact.getGivenName());
        args.put(StringUtils.join(myExpertise.size() > 5 ? myExpertise.subList(0, 5) : myExpertise,
                " " + StringPool.SLASH + " "));

        bit.put("key", "HAS_NEEDS_IN_MY_AREAS");
        bit.put("args", args);
        result.put(bit);

    }

    double industrySimilarity = getJaroWinklerDistance(me.getIndustry(), targetContact.getIndustry());
    double jobTitleSimilarity = getJaroWinklerDistance(me.getJobTitle(), targetContact.getJobTitle());
    double locationDistance;

    if (me.getLat() == 0 || me.getLng() == 0 || targetContact.getLat() == 0 || targetContact.getLng() == 0) {
        locationDistance = 100000;
    } else {
        locationDistance = getDistanceBetween(me.getLat(), me.getLng(), targetContact.getLat(),
                targetContact.getLng());
    }

    double locationSimilarity = 1.0 - (locationDistance / 1000.0);
    if (locationSimilarity < 0)
        locationSimilarity = 0;

    if (locationSimilarity > .5 && me.getCountry().equals(targetContact.getCountry())) {

        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        args.put(targetContact.getCity());
        bit.put("key", "IS_NEARBY");
        bit.put("args", args);
        result.put(bit);

    } else if (me.getCountry().equals(targetContact.getCountry())) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        bit.put("key", "LIVES_WORKS_IN_COUNTRY");
        bit.put("args", args);
        result.put(bit);

    }

    if (industrySimilarity > .7) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        args.put(targetContact.getIndustry());
        bit.put("key", "SIMILAR_INDUSTRY");
        bit.put("args", args);
        result.put(bit);

    }
    if (jobTitleSimilarity > .7) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        args.put(targetContact.getJobTitle());
        bit.put("key", "SIMILAR_JOB");
        bit.put("args", args);
        result.put(bit);

    }

    JSONArray words1o = JSONFactoryUtil.createJSONArray(me.getInterests());
    JSONArray words2o = JSONFactoryUtil.createJSONArray(targetContact.getInterests());

    List<String> words1 = new ArrayList<String>();
    List<String> words2 = new ArrayList<String>();
    final Map<String, Integer> count1 = new HashMap<String, Integer>();
    final Map<String, Integer> count2 = new HashMap<String, Integer>();
    final Map<String, Double> weight1 = new HashMap<String, Double>();
    final Map<String, Double> weight2 = new HashMap<String, Double>();

    for (int i = 0; i < words1o.length(); i++) {
        JSONObject o = words1o.getJSONObject(i);

        String word = o.getString("word");
        int count = o.getInt("count");
        double weight = o.getDouble("weight");

        words1.add(word);
        count1.put(word, count);
        weight1.put(word, weight);
    }

    for (int i = 0; i < words2o.length(); i++) {
        JSONObject o = words2o.getJSONObject(i);

        String word = o.getString("word");
        int count = o.getInt("count");
        double weight = o.getDouble("weight");

        words2.add(word);
        count2.put(word, count);
        weight2.put(word, weight);
    }

    Set<String> commonWords = new HashSet<String>(words1);
    commonWords.retainAll(words2);

    List<String> sortedCommon = new SortedArrayList<String>(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return (int) Math.floor(
                    ((((double) count1.get(o2) * weight1.get(o2)) + ((double) count2.get(o2) * weight2.get(o2)))
                            - (((double) count1.get(o1) * weight1.get(o1))
                                    + ((double) count2.get(o1) * weight2.get(o1)))));

        }
    });

    sortedCommon.addAll(commonWords);

    if (!sortedCommon.isEmpty()) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(StringUtils.join(sortedCommon.size() > 5 ? sortedCommon.subList(0, 5) : sortedCommon, " / "));
        bit.put("key", "SIMILAR_SKILLS_INTERESTS");
        bit.put("args", args);
        result.put(bit);

    }

    if (result.length() <= 0) {
        List<String> sortedTargetWords = new SortedArrayList<String>(new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return (int) Math.floor(((weight2.get(b) * (double) count2.get(b))
                        - (weight2.get(a) * (double) count2.get(a))));
            }
        });
        sortedTargetWords.addAll(words2);

        if (!sortedTargetWords.isEmpty()) {
            JSONObject bit = JSONFactoryUtil.createJSONObject();
            JSONArray args = JSONFactoryUtil.createJSONArray();
            args.put(StringUtils.join(
                    sortedTargetWords.size() > 3 ? sortedTargetWords.subList(0, 3) : sortedTargetWords, " / "));
            bit.put("key", "MIGHT_BE_INTERESTED");
            bit.put("args", args);
            result.put(bit);

        }
    }
    return result.toString();
}