Java Code Examples for org.json.JSONObject#opt()

The following examples show how to use org.json.JSONObject#opt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DConnectUtil.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * JSONの中に入っているuriを変換する.
 * <p>
 * <p>
 * 変換するuriはcontent://から始まるuriのみ変換する。<br/>
 * それ以外のuriは何も処理しない。
 * </p>
 *
 * @param settings DeviceConnect設定
 * @param root     変換するJSONObject
 * @throws JSONException JSONの解析に失敗した場合
 */
private static void convertUri(final DConnectSettings settings, final JSONObject root) throws JSONException {
    @SuppressWarnings("unchecked") // Using legacy API
    Iterator<String> it = root.keys();
    while (it.hasNext()) {
        String key = it.next();
        Object value = root.opt(key);
        if (value instanceof String) {
            if (isUriKey(key) && startWithContent((String) value)) {
                String u = createUri(settings, (String) value);
                root.put(key, u);
            }
        } else if (value instanceof JSONObject) {
            convertUri(settings, (JSONObject) value);
        } else if (value instanceof JSONArray) {
            JSONArray array = (JSONArray) value;
            int length = array.length();
            for (int i = 0; i < length; i++) {
                JSONObject json = array.optJSONObject(i);
                if (json != null) {
                    convertUri(settings, json);
                }
            }
        }
    }
}
 
Example 2
Source File: AuxCache.java    From react-native-image-filter-kit with MIT License 6 votes vote down vote up
@Nonnull
private static List<Integer> imageIndexes(final @Nonnull JSONObject config) {
  final ArrayList<Integer> indexes = new ArrayList<>();

  for (Iterator<String> iterator = config.keys(); iterator.hasNext();) {
    final JSONObject item = config.optJSONObject(iterator.next());

    if (item != null) {
      final Object image = item.opt("image");

      if (image instanceof Integer) {
        indexes.add((Integer) image);

      } else if (image instanceof JSONObject) {
        indexes.addAll(imageIndexes((JSONObject) image));
      }
    }
  }

  return indexes;
}
 
Example 3
Source File: LamiData.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets a {@link Number} object from a specific property of a
 * {@link JSONObject} object.
 *
 * @param obj
 *              JSON object from which to get the number
 * @param key
 *              Key of the property to read
 * @param useLong
 *              {@code true} to decode the number as a long integer
 * @return The decoded {@link Number} object
 * @throws JSONException If the property is not found
 */
private static @Nullable Number getNumberFromJsonObject(JSONObject obj,
        String key, boolean useLong, boolean acceptInfinity) throws JSONException {
    Object numberObj = obj.opt(key);

    if (numberObj == null) {
        return null;
    }

    if (acceptInfinity && numberObj instanceof String) {
        if (numberObj.equals(LamiStrings.NEG_INF)) {
            return Double.NEGATIVE_INFINITY;
        } else if (numberObj.equals(LamiStrings.POS_INF)) {
            return Double.POSITIVE_INFINITY;
        }

        throw new JSONException("Invalid number: " + numberObj); //$NON-NLS-1$
    }

    if (useLong) {
        return obj.getLong(key);
    }

    return obj.getDouble(key);
}
 
Example 4
Source File: ExampleInstrumentedTest.java    From XmlToJson with Apache License 2.0 5 votes vote down vote up
@Test
    public void issueGitHub3_Test() throws Exception {

        Context context = InstrumentationRegistry.getTargetContext();
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = assetManager.open("bug_3_github.xml");

        XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null)
                .forceList("/biblio/auteur")
                .forceList("/biblio/auteur/ouvrages/livre")
                .build();

//        String jsonStr = xmlToJson.toString();
        JSONObject json = xmlToJson.toJson();
        JSONObject biblio = json.getJSONObject("biblio");
        JSONArray auteurs = biblio.getJSONArray("auteur");
        int nbAuteurs = auteurs.length();
        assertEquals(nbAuteurs, 2);
        for (int i = 0; i < nbAuteurs; ++i) {
            JSONObject auteur = auteurs.getJSONObject(i);
            String id = auteur.optString("id");
            String nom = auteur.optString("nom");
            assertTrue("id not found", !TextUtils.isEmpty(id));
            assertTrue("nom not found", !TextUtils.isEmpty(nom));
            JSONObject ouvrages = auteur.getJSONObject("ouvrages");
            String quantite = ouvrages.getString("quantite");
            assertTrue("quantite not found", !TextUtils.isEmpty(quantite));
            Object livres = ouvrages.opt("livre");
            assertTrue("livre is not an array", livres instanceof JSONArray);
        }

        inputStream.close();
    }
 
Example 5
Source File: FormViewerTemplateBuilder.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void getFields(JSONArray nodes, JSONArray container) throws Exception {
	for (int i = 0; i < nodes.length(); i++) {
		JSONObject node = (JSONObject) nodes.get(i);
		
		JSONArray children = (JSONArray) node.opt("children");
		
		if (children != null && children.length() > 0) {
			// entity node
			getFields(children, container);
		} else {
			// field leaf
			container.put(node.get("id"));
		}
	}
}
 
Example 6
Source File: FollowQueryService.java    From symphonyx with Apache License 2.0 5 votes vote down vote up
/**
 * Gets following tags of the specified follower.
 *
 * @param followerId the specified follower id
 * @param currentPageNum the specified page number
 * @param pageSize the specified page size
 * @return result json object, for example,      <pre>
 * {
 *     "paginationRecordCount": int,
 *     "rslts": java.util.List[{
 *         Tag
 *     }, ....]
 * }
 * </pre>
 *
 * @throws ServiceException service exception
 */
public JSONObject getFollowingTags(final String followerId, final int currentPageNum, final int pageSize) throws ServiceException {
    final JSONObject ret = new JSONObject();
    final List<JSONObject> records = new ArrayList<JSONObject>();

    ret.put(Keys.RESULTS, (Object) records);
    ret.put(Pagination.PAGINATION_RECORD_COUNT, 0);

    try {
        final JSONObject result = getFollowings(followerId, Follow.FOLLOWING_TYPE_C_TAG, currentPageNum, pageSize);
        @SuppressWarnings("unchecked")
        final List<JSONObject> followings = (List<JSONObject>) result.opt(Keys.RESULTS);

        for (final JSONObject follow : followings) {
            final String followingId = follow.optString(Follow.FOLLOWING_ID);
            final JSONObject tag = tagRepository.get(followingId);

            if (null == tag) {
                LOGGER.log(Level.WARN, "Not found tag[id=" + followingId + ']');

                continue;
            }

            records.add(tag);
        }

        ret.put(Pagination.PAGINATION_RECORD_COUNT, result.optInt(Pagination.PAGINATION_RECORD_COUNT));
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Gets following tags of follower[id=" + followerId + "] failed", e);
    }

    return ret;
}
 
Example 7
Source File: JsonUtil.java    From Abelana-Android with Apache License 2.0 5 votes vote down vote up
static boolean jsonObjectContainsValue(JSONObject jsonObject, Object value) {
    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        Object thisValue = jsonObject.opt(keys.next());
        if (thisValue != null && thisValue.equals(value)) {
            return true;
        }
    }
    return false;
}
 
Example 8
Source File: JwtClaimSet.java    From oxAuth with MIT License 5 votes vote down vote up
public void load(JSONObject jsonObject) {
    claims.clear();

    for (Iterator<String> it = jsonObject.keys(); it.hasNext(); ) {
        String key = it.next();
        Object value = jsonObject.opt(key);

        claims.put(key, value);
    }
}
 
Example 9
Source File: JsonDemo.java    From java-tutorial with MIT License 5 votes vote down vote up
private static Object jsonObjectToObject(JSONObject obj, Field field) throws JSONException {
    //field.getType:获取属性声明时类型对象(返回class对象)
    switch (getType(field.getType())) {
        case 0:
            return obj.opt(field.getName());
        case 1:
            return obj.optInt(field.getName());
        case 2:
            return obj.optLong(field.getName());
        case 3:
        case 4:
            return obj.optDouble(field.getName());
        case 5:
            return obj.optBoolean(field.getName());
        case 6:
        case 7:
            //JsonArray型
        case 8:
            return obj.optJSONArray(field.getName());
        case 9:
            return jsonArrayToList(obj.optJSONArray(field.getName()));
        case 10:
            return jsonObjectToMap(obj.optJSONObject(field.getName()));
        default:
            return null;
    }
}
 
Example 10
Source File: ChromeBackupAgent.java    From delion with Apache License 2.0 5 votes vote down vote up
private Object readChromePref(JSONObject json, String pref[]) {
    JSONObject finalParent = json;
    for (int i = 0; i < pref.length - 1; i++) {
        finalParent = finalParent.optJSONObject(pref[i]);
        if (finalParent == null) return null;
    }
    return finalParent.opt(pref[pref.length - 1]);
}
 
Example 11
Source File: JSONObjectUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定 key 数据
 * @param jsonObject {@link JSONObject}
 * @param key        Key
 * @param <T>        泛型
 * @return 指定 key 数据
 */
public static <T> T opt(final JSONObject jsonObject, final String key) {
    if (jsonObject != null && key != null) {
        try {
            return (T) jsonObject.opt(key);
        } catch (Exception e) {
            LogPrintUtils.eTag(TAG, e, "opt - JSONObject");
        }
    }
    return null;
}
 
Example 12
Source File: JsonUtil.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
static boolean jsonObjectContainsValue(JSONObject jsonObject, Object value) {
    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        Object thisValue = jsonObject.opt(keys.next());
        if (thisValue != null && thisValue.equals(value)) {
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: JsonUtil.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 5 votes vote down vote up
static boolean jsonObjectContainsValue(JSONObject jsonObject, Object value) {
    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        Object thisValue = jsonObject.opt(keys.next());
        if (thisValue != null && thisValue.equals(value)) {
            return true;
        }
    }
    return false;
}
 
Example 14
Source File: UserProcessor.java    From symphonyx with Apache License 2.0 4 votes vote down vote up
/**
 * Shows user home follower users page.
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @param userName the specified user name
 * @throws Exception exception
 */
@RequestProcessing(value = "/member/{userName}/followers", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = StopwatchEndAdvice.class)
public void showHomeFollowers(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response, final String userName) throws Exception {
    final JSONObject user = (JSONObject) request.getAttribute(User.USER);

    request.setAttribute(Keys.TEMAPLTE_DIR_NAME, Symphonys.get("skinDirName"));
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("/home/followers.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    filler.fillHeaderAndFooter(request, response, dataModel);

    String pageNumStr = request.getParameter("p");
    if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
        pageNumStr = "1";
    }

    final int pageNum = Integer.valueOf(pageNumStr);

    final int pageSize = Symphonys.getInt("userHomeFollowersCnt");
    final int windowSize = Symphonys.getInt("userHomeFollowersWindowSize");

    fillHomeUser(dataModel, user);

    final String followingId = user.optString(Keys.OBJECT_ID);
    dataModel.put(Follow.FOLLOWING_ID, followingId);

    final JSONObject followerUsersResult = followQueryService.getFollowerUsers(followingId, pageNum, pageSize);
    final List<JSONObject> followerUsers = (List) followerUsersResult.opt(Keys.RESULTS);
    dataModel.put(Common.USER_HOME_FOLLOWER_USERS, followerUsers);
    avatarQueryService.fillUserAvatarURL(user);

    final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
    if (isLoggedIn) {
        final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
        final String followerId = currentUser.optString(Keys.OBJECT_ID);

        final boolean isFollowing = followQueryService.isFollowing(followerId, followingId);
        dataModel.put(Common.IS_FOLLOWING, isFollowing);

        for (final JSONObject followerUser : followerUsers) {
            final String homeUserFollowerUserId = followerUser.optString(Keys.OBJECT_ID);

            followerUser.put(Common.IS_FOLLOWING, followQueryService.isFollowing(followerId, homeUserFollowerUserId));
        }
    }

    user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));

    final int followerUserCnt = followerUsersResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
    final int pageCount = (int) Math.ceil((double) followerUserCnt / (double) pageSize);

    final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
    if (!pageNums.isEmpty()) {
        dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
        dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
    }

    dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
    dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
}
 
Example 15
Source File: Keyframe.java    From atlas with Apache License 2.0 4 votes vote down vote up
static <T> Keyframe<T> newInstance(JSONObject json, LottieComposition composition, float scale,
    AnimatableValue.Factory<T> valueFactory) {
  PointF cp1 = null;
  PointF cp2 = null;
  float startFrame = 0;
  T startValue = null;
  T endValue = null;
  Interpolator interpolator = null;

  if (json.has("t")) {
    startFrame = (float) json.optDouble("t", 0);
    Object startValueJson = json.opt("s");
    if (startValueJson != null) {
      startValue = valueFactory.valueFromObject(startValueJson, scale);
    }

    Object endValueJson = json.opt("e");
    if (endValueJson != null) {
      endValue = valueFactory.valueFromObject(endValueJson, scale);
    }

    JSONObject cp1Json = json.optJSONObject("o");
    JSONObject cp2Json = json.optJSONObject("i");
    if (cp1Json != null && cp2Json != null) {
      cp1 = JsonUtils.pointFromJsonObject(cp1Json, scale);
      cp2 = JsonUtils.pointFromJsonObject(cp2Json, scale);
    }

    boolean hold = json.optInt("h", 0) == 1;

    if (hold) {
      endValue = startValue;
      // TODO: create a HoldInterpolator so progress changes don't invalidate.
      interpolator = LINEAR_INTERPOLATOR;
    } else if (cp1 != null) {
      interpolator = PathInterpolatorCompat.create(
          cp1.x / scale, cp1.y / scale, cp2.x / scale, cp2.y / scale);
    } else {
      interpolator = LINEAR_INTERPOLATOR;
    }
  } else {
    startValue = valueFactory.valueFromObject(json, scale);
    endValue = startValue;
  }
  return new Keyframe<>(composition, startValue, endValue, interpolator, startFrame, null);
}
 
Example 16
Source File: AccountTxPager.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
private void onTransactions(JSONObject responseResult) {
    final JSONArray transactions = responseResult.getJSONArray("transactions");
    final int ledger_index_max = responseResult.optInt("ledger_index_max");
    final int ledger_index_min = responseResult.optInt("ledger_index_min");
    final Object newMarker = responseResult.opt("marker");

    onPage.onPage(new Page() {
        ArrayList<TransactionResult> txns = null;

        @Override
        public boolean hasNext() {
            return newMarker != null;
        }

        @Override
        public void requestNext() {
            if (hasNext()) {
                walkAccountTx(newMarker);
            }
        }

        @Override
        public long ledgerMax() {
            return ledger_index_max;
        }

        @Override
        public long ledgerMin() {
            return ledger_index_min;
        }

        @Override
        public int size() {
            return transactions.length();
        }

        @Override
        public ArrayList<TransactionResult> transactionResults() {
            if (txns == null) {
                txns = new ArrayList<TransactionResult>();
                for (int i = 0; i < transactions.length(); i++) {
                    JSONObject jsonObject = transactions.optJSONObject(i);
                    txns.add(new TransactionResult(jsonObject,
                            TransactionResult.Source.request_account_tx_binary));
                }
            }
            return txns;
        }

        @Override
        public JSONArray transactionsJSON() {
            return transactions;
        }
    });
}
 
Example 17
Source File: ColorParser.java    From react-native-navigation with MIT License 4 votes vote down vote up
public static Colour parse(JSONObject json, String color) {
    if (json.has(color)) {
        return json.opt(color) instanceof Integer ? new Colour(json.optInt(color)) : new DontApplyColour();
    }
    return new NullColor();
}
 
Example 18
Source File: AirMapFlightPlan.java    From AirMapSDK-Android with Apache License 2.0 4 votes vote down vote up
@Override
public AirMapFlightPlan constructFromJson(JSONObject json) {
    if (json != null) {
        setPlanId(optString(json, "id"));
        setFlightId(optString(json, "flight_id"));
        setTakeoffCoordinate(new Coordinate(json.optDouble("takeoff_latitude", 0), json.optDouble("takeoff_longitude", 0)));
        setMaxAltitude((float) json.optDouble("max_altitude_agl"));
        setNotify(json.optBoolean("notify"));
        setPilotId(optString(json, "pilot_id"));
        setAircraftId(optString(json, "aircraft_id"));
        setPublic(json.optBoolean("public"));
        setBuffer((float) json.optDouble("buffer"));

        JSONObject geometryGeoJSON = json.optJSONObject("geometry");
        if (geometryGeoJSON != null) {
            setGeometry(geometryGeoJSON.toString());
        }

        rulesetIds = new ArrayList<>();
        JSONArray rulesetsJson = json.optJSONArray("rulesets");
        for (int i = 0; rulesetsJson != null && i < rulesetsJson.length(); i++) {
            rulesetIds.add(optString(rulesetsJson, i));
        }

        flightFeatureValues = new HashMap<>();
        JSONObject flightFeaturesJSON = json.optJSONObject("flight_features");
        if (flightFeaturesJSON != null) {
            Iterator<String> featuresItr = flightFeaturesJSON.keys();
            while (featuresItr.hasNext()) {
                String key = featuresItr.next();
                Object value = flightFeaturesJSON.opt(key);
                if (value instanceof Serializable) {
                    FlightFeatureValue flightFeatureValue = new FlightFeatureValue(key, (Serializable) value);
                    flightFeatureValues.put(key, flightFeatureValue);
                } else {
                    Timber.e("Got non-Serializable object: %s", String.valueOf(value));
                }
            }
        }

        //Created at
        if (json.has("created_at")) {
            setCreatedAt(getDateFromIso8601String(optString(json, "created_at")));
        } else if (json.has("creation_date")) {
            setCreatedAt(getDateFromIso8601String(optString(json, "creation_date")));
        }

        String startTime = optString(json, "start_time");
        String endTime = optString(json, "end_time");
        if (!TextUtils.isEmpty(startTime) && !startTime.equals("now")) {
            // if start date is before now, set it to now and shift end time
            Date startDate = getDateFromIso8601String(startTime);
            Date endDate = getDateFromIso8601String(endTime);
            long duration = endDate.getTime() - startDate.getTime();
            if (new Date().after(startDate)) {
                setStartsAt(new Date());
                setEndsAt(new Date(getStartsAt().getTime() + duration));
            } else {
                setStartsAt(startDate);
                setEndsAt(new Date(startDate.getTime() + duration));
            }
        } else {
            setEndsAt(getDateFromIso8601String(endTime));
        }
    }
    return this;
}
 
Example 19
Source File: UserProcessor.java    From symphonyx with Apache License 2.0 4 votes vote down vote up
/**
 * Shows user home following users page.
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @param userName the specified user name
 * @throws Exception exception
 */
@RequestProcessing(value = "/member/{userName}/following/users", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = StopwatchEndAdvice.class)
public void showHomeFollowingUsers(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response, final String userName) throws Exception {
    final JSONObject user = (JSONObject) request.getAttribute(User.USER);

    request.setAttribute(Keys.TEMAPLTE_DIR_NAME, Symphonys.get("skinDirName"));
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("/home/following-users.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    filler.fillHeaderAndFooter(request, response, dataModel);

    String pageNumStr = request.getParameter("p");
    if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
        pageNumStr = "1";
    }

    final int pageNum = Integer.valueOf(pageNumStr);

    final int pageSize = Symphonys.getInt("userHomeFollowingUsersCnt");
    final int windowSize = Symphonys.getInt("userHomeFollowingUsersWindowSize");

    fillHomeUser(dataModel, user);

    final String followingId = user.optString(Keys.OBJECT_ID);
    dataModel.put(Follow.FOLLOWING_ID, followingId);
    avatarQueryService.fillUserAvatarURL(user);

    final JSONObject followingUsersResult = followQueryService.getFollowingUsers(followingId, pageNum, pageSize);
    final List<JSONObject> followingUsers = (List<JSONObject>) followingUsersResult.opt(Keys.RESULTS);
    dataModel.put(Common.USER_HOME_FOLLOWING_USERS, followingUsers);

    final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
    if (isLoggedIn) {
        final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
        final String followerId = currentUser.optString(Keys.OBJECT_ID);

        final boolean isFollowing = followQueryService.isFollowing(followerId, followingId);
        dataModel.put(Common.IS_FOLLOWING, isFollowing);

        for (final JSONObject followingUser : followingUsers) {
            final String homeUserFollowingUserId = followingUser.optString(Keys.OBJECT_ID);

            followingUser.put(Common.IS_FOLLOWING, followQueryService.isFollowing(followerId, homeUserFollowingUserId));
        }
    }

    user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));

    final int followingUserCnt = followingUsersResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
    final int pageCount = (int) Math.ceil((double) followingUserCnt / (double) pageSize);

    final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
    if (!pageNums.isEmpty()) {
        dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
        dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
    }

    dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
    dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
}
 
Example 20
Source File: SalesforceProvisioningConnector.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * authenticate to salesforce API.
 */
private String authenticate() throws IdentityProvisioningException {

    boolean isDebugEnabled = log.isDebugEnabled();

    HttpClient httpclient = new HttpClient();

    String url = configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.OAUTH2_TOKEN_ENDPOINT);

    PostMethod post = new PostMethod(StringUtils.isNotBlank(url) ?
            url : IdentityApplicationConstants.SF_OAUTH2_TOKEN_ENDPOINT);

    post.addParameter(SalesforceConnectorConstants.CLIENT_ID,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.CLIENT_ID));
    post.addParameter(SalesforceConnectorConstants.CLIENT_SECRET,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.CLIENT_SECRET));
    post.addParameter(SalesforceConnectorConstants.PASSWORD,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.PASSWORD));
    post.addParameter(SalesforceConnectorConstants.GRANT_TYPE,
            SalesforceConnectorConstants.GRANT_TYPE_PASSWORD);
    post.addParameter(SalesforceConnectorConstants.USERNAME,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.USERNAME));

    StringBuilder sb = new StringBuilder();
    try {
        // send the request
        int responseStatus = httpclient.executeMethod(post);
        if (isDebugEnabled) {
            log.debug("Authentication to salesforce returned with response code: "
                    + responseStatus);
        }

        sb.append("HTTP status " + post.getStatusCode() + " creating user\n\n");

        if (post.getStatusCode() == HttpStatus.SC_OK) {
            JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(
                    post.getResponseBodyAsStream())));
            if (isDebugEnabled) {
                log.debug("Authenticate response: " + response.toString(2));
            }

            Object attributeValObj = response.opt("access_token");
            if (attributeValObj instanceof String) {
                if (isDebugEnabled) {
                    log.debug("Access token is : " + (String) attributeValObj);
                }
                return (String) attributeValObj;
            } else {
                log.error("Authentication response type : " + attributeValObj.toString()
                        + " is invalide");
            }
        } else {
            log.error("recieved response status code :" + post.getStatusCode() + " text : "
                    + post.getStatusText());
        }
    } catch (JSONException | IOException e) {
        throw new IdentityProvisioningException("Error in decoding response to JSON", e);
    } finally {
        post.releaseConnection();
    }

    return "";
}