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

The following examples show how to use org.json.JSONObject#has() . 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: StreamUrl.java    From uPods-android with Apache License 2.0 7 votes vote down vote up
public StreamUrl(JSONObject jsonItem) {
    try {
        this.url = jsonItem.has("url") ? jsonItem.getString("url") : "";
        this.bitrate = jsonItem.has("bitrate") ? jsonItem.getString("bitrate") : "";
        this.isAlive = true;

        if (bitrate.contains("000")) {
            bitrate = bitrate.replace("000", "");
        }

        if (bitrate.equals("null") || bitrate.equals("0")) {
            bitrate = "";
        }
        if (!bitrate.matches("[0-9]+")) {
            bitrate = "";
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: SmsSingleSenderResult.java    From qcloudsms_java with MIT License 6 votes vote down vote up
@Override
public SmsSingleSenderResult parseFromHTTPResponse(HTTPResponse response)
        throws JSONException {

    JSONObject json = parseToJson(response);

    result = json.getInt("result");
    errMsg = json.getString("errmsg");
    if (json.has("sid")) {
        sid = json.getString("sid");
    }
    if (json.has("fee")) {
        fee = json.getInt("fee");
    }
    if (json.has("ext")) {
        ext = json.getString("ext");
    }

    return this;
}
 
Example 3
Source File: Hook12306Impl2.java    From 12306XposedPlugin with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发起网络请求
 *
 * @param request RpcRequest
 * @param <T>     T
 * @return response
 */
@WorkerThread
private <T> T rpcWithBaseDTO(RpcRequest<T> request) {
    try {
        JSONObject requestData = request.requestData();
        JSONObject baseDTO = createBaseDTO();
        if (requestData.has("_requestBody")) {
            requestData.optJSONObject("_requestBody").put("baseDTO", baseDTO);
        } else {
            requestData.put("baseDTO", baseDTO);
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(requestData);
        Object result = rpcCallMethod.invoke(null, request.operationType(),
                jsonArray.toString(), "", true, null, null, false, null, 0, "", request.isHttpGet(),
                request.signType());
        String response = (String) getResponseMethod.invoke(result);
        return request.onResponse(response);
    } catch (Exception e) {
        Log.e(TAG, "rpcWithBaseDTO", e);
    }
    return null;
}
 
Example 4
Source File: WifiUSourceData.java    From Easer with GNU General Public License v3.0 6 votes vote down vote up
WifiUSourceData(@NonNull String data, @NonNull PluginDataFormat format, int version) throws IllegalStorageDataException {
    switch (format) {
        default:
            try {
                if (version < C.VERSION_WIFI_ADD_BSSID) {
                    JSONArray jsonArray = new JSONArray(data);
                    readFromJsonArray(jsonArray);
                } else {
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.has(K_ESSID)) {
                        mode_essid = true;
                        readFromJsonArray(jsonObject.getJSONArray(K_ESSID));
                    } else {
                        mode_essid = false;
                        readFromJsonArray(jsonObject.getJSONArray(K_BSSID));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                throw new IllegalStorageDataException(e);
            }
    }
}
 
Example 5
Source File: ProviderApiManagerBase.java    From bitmask_android with GNU General Public License v3.0 6 votes vote down vote up
private Bundle register(Provider provider, String username, String password) {
    JSONObject stepResult = null;
    OkHttpClient okHttpClient = clientGenerator.initSelfSignedCAHttpClient(provider.getCaCert(), stepResult);
    if (okHttpClient == null) {
        return backendErrorNotification(stepResult, username);
    }

    LeapSRPSession client = new LeapSRPSession(username, password);
    byte[] salt = client.calculateNewSalt();

    BigInteger password_verifier = client.calculateV(username, password, salt);

    JSONObject api_result = sendNewUserDataToSRPServer(provider.getApiUrlWithVersion(), username, new BigInteger(1, salt).toString(16), password_verifier.toString(16), okHttpClient);

    Bundle result = new Bundle();
    if (api_result.has(ERRORS) || api_result.has(BACKEND_ERROR_KEY))
        result = backendErrorNotification(api_result, username);
    else {
        result.putString(CREDENTIALS_USERNAME, username);
        result.putString(CREDENTIALS_PASSWORD, password);
        result.putBoolean(BROADCAST_RESULT_KEY, true);
    }

    return result;
}
 
Example 6
Source File: FrameLayoutStyler.java    From dynamico with Apache License 2.0 5 votes vote down vote up
@Override
public View style(View view, JSONObject attributes) throws Exception {
    super.style(view, attributes);

    FrameLayout frameLayout = (FrameLayout) view;

    if(attributes.has("measureAllChildren")) {
        frameLayout.setMeasureAllChildren(attributes.getBoolean("measureAllChildren"));
    }

    if(attributes.has("foregroundGravity")) {
        String gravity = attributes.getString("foregroundGravity");

        if(gravity.equalsIgnoreCase("start")) {
            frameLayout.setForegroundGravity(Gravity.START);
        }else if(gravity.equalsIgnoreCase("top")) {
            frameLayout.setForegroundGravity(Gravity.TOP);
        }else if(gravity.equalsIgnoreCase("end")) {
            frameLayout.setForegroundGravity(Gravity.END);
        }else if(gravity.equalsIgnoreCase("bottom")) {
            frameLayout.setForegroundGravity(Gravity.BOTTOM);
        }else if(gravity.equalsIgnoreCase("center")) {
            frameLayout.setForegroundGravity(Gravity.CENTER);
        }else if(gravity.equalsIgnoreCase("center_horizontal")) {
            frameLayout.setForegroundGravity(Gravity.CENTER_HORIZONTAL);
        }else if(gravity.equalsIgnoreCase("center_vertical")) {
            frameLayout.setForegroundGravity(Gravity.CENTER_VERTICAL);
        }
    }

    return frameLayout;
}
 
Example 7
Source File: OidcHelper.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Attempts to find a user in the Entando database for the username found in the accesstoken. If none is found,
 * it constructs an in-memory UserDetails object and populates its attributes from attribytes found in
 * the token.
 * @param accessToken
 * @return
 * @throws ApsSystemException
 */
public UserDetails getOidcUser(String accessToken) throws ApsSystemException {
    String[] split_string = accessToken.split("\\.");
    String base64EncodedBody = split_string[1];
    Base64 base64Url = new Base64(true);
    logger.info("---------------------TOKEN-----------------------");
    logger.info(new String(base64Url.decode(split_string[0])));
    logger.info("--------------------------------------------");
    String body = new String(base64Url.decode(base64EncodedBody));
    logger.info(body);
    logger.info("--------------------------------------------");
    JSONObject obj = new JSONObject(body);
    String username = null;
    if (obj.has(USERNAME_PARAM_NAME)) {
        username = obj.getString(USERNAME_PARAM_NAME);
        logger.info("USERNAME -> " + username);
    } else {
        username = "tempUser";
        logger.info("\"" + USERNAME_PARAM_NAME + "\" ATTRIBUTE NOT FOUND");
        logger.info("DEFAULT USERNAME -> " + username);
    }
    if (StringUtils.isEmpty(username)) {
        username = "tempUser";
        logger.info("\"" + USERNAME_PARAM_NAME + "\" ATTRIBUTE EMPTY OR NOT FOUND");
        logger.info("DEFAULT USERNAME -> " + username);
    }
    UserDetails user = authenticationProviderManager.getUser(username);
    if (null == user) {
        logger.info("CREATING UserDetails object for  " + username);
        user = new User();
        ((User) user).setUsername(username);
        ((User) user).setPassword(RESERVED_PASSWORD);
        UserProfile profile = new UserProfile();
        ((User) user).setProfile(profile);
        copyAttributes(obj, profile);
    }else{
        logger.info("WARNING!!! UserDetails object found for  " + username);
    }
    return user;
}
 
Example 8
Source File: PublishFormFragment.java    From lbry-android with MIT License 5 votes vote down vote up
private static int tryParseDuration(JSONObject streamObject) {
    String durationString = Helper.getJSONString("duration", "0", streamObject);
    double parsedDuration = Helper.parseDouble(durationString, 0);
    if (parsedDuration > 0) {
        return Double.valueOf(parsedDuration).intValue();
    }

    try {
        if (streamObject.has("tags") && !streamObject.isNull("tags")) {
            JSONObject tags = streamObject.getJSONObject("tags");
            String tagDurationString = Helper.getJSONString("DURATION", null, tags);
            if (Helper.isNull(tagDurationString)) {
                tagDurationString = Helper.getJSONString("duration", null, tags);
            }
            if (!Helper.isNullOrEmpty(tagDurationString) && tagDurationString.indexOf(':') > -1) {
                String[] parts = tagDurationString.split(":");
                if (parts.length == 3) {
                    int hours = Helper.parseInt(parts[0], 0);
                    int minutes = Helper.parseInt(parts[1], 0);
                    int seconds = Helper.parseDouble(parts[2], 0).intValue();
                    return (hours * 60 * 60) + (minutes * 60) + seconds;
                }
            }

        }
    } catch (JSONException ex) {
        return 0;
    }

    return 0;
}
 
Example 9
Source File: CodewindApplicationFactory.java    From codewind-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private static int getPort(JSONObject portsObj, String key) throws JSONException {
	int portNum = -1;
	if (portsObj != null && portsObj.has(key)) {
		String port = portsObj.getString(key);
		if (port != null && !port.isEmpty()) {
			portNum = CoreUtil.parsePort(port);
		}
	}
	return portNum;
}
 
Example 10
Source File: AnimatablePathValue.java    From atlas with Apache License 2.0 5 votes vote down vote up
static AnimatableValue<PointF> createAnimatablePathOrSplitDimensionPath(
    JSONObject json, LottieComposition composition) {
  if (json.has("k")) {
    return new AnimatablePathValue(json.opt("k"), composition);
  } else {
    return new AnimatableSplitDimensionPathValue(
        AnimatableFloatValue.Factory.newInstance(json.optJSONObject("x"), composition),
        AnimatableFloatValue.Factory.newInstance(json.optJSONObject("y"), composition));
  }
}
 
Example 11
Source File: CodewindConnection.java    From codewind-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public ImagePushRegistryInfo requestGetPushRegistry() throws IOException, JSONException {
	final URI uri = baseUri.resolve(CoreConstants.APIPATH_BASE + "/" + CoreConstants.APIPATH_IMAGEPUSHREGISTRY);
	HttpResult result = HttpUtil.get(uri, getAuthToken(false));
	if (hasAuthFailure(result)) {
		result = HttpUtil.get(uri, getAuthToken(true));
	}
	checkResult(result, uri, true);
	
	JSONObject obj = new JSONObject(result.response);
	if (obj.has(CoreConstants.KEY_IMAGE_PUSH_REGISTRY) && obj.getBoolean(CoreConstants.KEY_IMAGE_PUSH_REGISTRY)) {
		return new ImagePushRegistryInfo(obj);
	}
	return null;
}
 
Example 12
Source File: JSONResolver.java    From Utils with Apache License 2.0 4 votes vote down vote up
private static void fillField(Object entity, Field field,
                              JSONObject jsonObject) throws Exception {
    JSONNode jsonNode = field.getAnnotation(JSONNode.class);
    if (jsonNode != null) {
        String jsonKey = jsonNode.key();
        if (jsonObject.has(jsonKey)) {
            Class<?> fieldClazz = field.getType();
            if (isBasicType(fieldClazz)) {
                Object value = jsonObject.get(jsonKey);
                jsonObject.remove(jsonKey);
                try {
                    if (isWrapType(fieldClazz)
                            || String.class.isAssignableFrom(fieldClazz)) {
                        // If it's wrapped type, then must have the constructs
                        Constructor<?> cons = fieldClazz
                                .getConstructor(String.class);
                        Object attrValue = cons.newInstance(value
                                .toString());
                        field.set(entity, attrValue);
                    } else {
                        field.set(entity, value);
                    }
                } catch (Exception e) {
                    String error = "invalid value[" + value
                            + "] for field[" + field.getName()
                            + "]; valueClass[" + value.getClass()
                            + "]; annotationName[" + jsonKey + "]";
                    throw new JSONException(error);
                }
            } else {
                Object objValue = jsonObject.get(jsonKey);
                if (objValue != null) {
                    if (List.class.isAssignableFrom(fieldClazz)) {
                        List<Object> listValue = jsonArray2List(
                                jsonObject.getJSONArray(jsonKey),
                                fieldClazz, field.getGenericType());
                        field.set(entity, listValue);
                    } else if (fieldClazz.isArray()) {
                        field.set(
                                entity,
                                jsonArray2Array(
                                        jsonObject.getJSONArray(jsonKey),
                                        fieldClazz));
                    } else {
                        field.set(
                                entity,
                                fromJson(jsonObject.getJSONObject(jsonKey),
                                        fieldClazz));
                    }
                }
            }
        }
    }
}
 
Example 13
Source File: UDApplet.java    From VideoOS-Android-SDK with GNU General Public License v3.0 4 votes vote down vote up
@Override
        public Varargs invoke(Varargs args) {
            int fixIndex = VenvyLVLibBinder.fixIndex(args);
            if (args.narg() > fixIndex) {
                final LuaTable table = LuaUtil.getTable(args, fixIndex + 2);
                try {
                    String str = JsonUtil.toString(table);
                    JSONObject jsonObject = new JSONObject(str);
//                    VenvyLog.d("openAds : " + jsonObject.toString());
                    if (jsonObject.has("targetType")) {
                        String targetType = jsonObject.optString("targetType");
                        JSONObject linkData = jsonObject.optJSONObject("linkData");
                        String downAPI = jsonObject.optString("downloadApkUrl");
                        // targetType  1 落地页 2 deepLink 3 下载
                        if (targetType.equalsIgnoreCase("3")) {
                            JSONObject downloadTrackLink = jsonObject.optJSONObject("downloadTrackLink");
                            Bundle trackData = new Bundle();
                            trackData.putString(VenvyObservableTarget.Constant.CONSTANT_DOWNLOAD_API, downAPI);
                            trackData.putStringArray("isTrackLinks", JsonUtil.toStringArray(downloadTrackLink.optJSONArray("isTrackLinks")));
                            trackData.putStringArray("dsTrackLinks", JsonUtil.toStringArray(downloadTrackLink.optJSONArray("dsTrackLinks")));
                            trackData.putStringArray("dfTrackLinks", JsonUtil.toStringArray(downloadTrackLink.optJSONArray("dfTrackLinks")));
                            trackData.putStringArray("instTrackLinks", JsonUtil.toStringArray(downloadTrackLink.optJSONArray("instTrackLinks")));
                            trackData.putString("launchPlanId",jsonObject.optString("launchPlanId"));
                            ObservableManager.getDefaultObserable().sendToTarget(VenvyObservableTarget.TAG_DOWNLOAD_TASK, trackData);
                        } else {
                            // 走Native:widgetNotify()  逻辑
                            WidgetInfo.Builder builder = new WidgetInfo.Builder()
                                    .setWidgetActionType(WidgetInfo.WidgetActionType.ACTION_OPEN_URL)
                                    .setUrl("");
                            if (targetType.equalsIgnoreCase("1")) {
                                builder.setLinkUrl(linkData.optString("linkUrl"));
                            } else if (targetType.equalsIgnoreCase("2")) {
                                builder.setLinkUrl(linkData.optString("linkUrl"));
                                builder.setDeepLink(linkData.optString("deepLink"));
                            }
                            WidgetInfo widgetInfo = builder.build();
                            if (platform.getWidgetClickListener() != null) {
                                platform.getWidgetClickListener().onClick(widgetInfo);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return LuaValue.NIL;
        }
 
Example 14
Source File: PLJSONLoader.java    From panoramagl with Apache License 2.0 4 votes vote down vote up
protected boolean parseCameraJSON(PLIPanorama panorama) {
    try {
        JSONObject camera = mJSON.getJSONObject("camera");
        if (camera != null) {
            PLIPanorama oldPanorama = mView.getPanorama();
            PLICamera oldCamera = (oldPanorama != null && !(oldPanorama instanceof PLBlankPanorama) ? oldPanorama.getCamera() : null);
            PLICamera currentCamera = panorama.getCamera();
            PLCameraParameters keep = (oldCamera != null && camera.has("keep") ? PLCameraParameterType.checkCameraParametersWithStringMask(camera.getString("keep")) : PLCameraParameterType.checkCameraParametersWithMask(PLCameraParameterType.PLCameraParameterTypeNone));
            float pitch = currentCamera.getInitialPitch(), yaw = currentCamera.getInitialYaw();
            if (keep.atvMin)
                currentCamera.setPitchMin(oldCamera.getPitchMin());
            else if (camera.has("atvMin"))
                currentCamera.setPitchMin((float) camera.getDouble("atvMin"));
            if (keep.atvMax)
                currentCamera.setPitchMax(oldCamera.getPitchMax());
            else if (camera.has("atvMax"))
                currentCamera.setPitchMax((float) camera.getDouble("atvMax"));
            if (keep.athMin)
                currentCamera.setYawMin(oldCamera.getYawMin());
            else if (camera.has("athMin"))
                currentCamera.setYawMin((float) camera.getDouble("athMin"));
            if (keep.athMax)
                currentCamera.setYawMax(oldCamera.getYawMax());
            else if (camera.has("athMax"))
                currentCamera.setYawMax((float) camera.getDouble("athMax"));
            if (keep.reverseRotation)
                currentCamera.setReverseRotation(oldCamera.isReverseRotation());
            else if (camera.has("reverseRotation"))
                currentCamera.setReverseRotation(camera.getBoolean("reverseRotation"));
            if (keep.rotationSensitivity)
                currentCamera.setRotationSensitivity(oldCamera.getRotationSensitivity());
            else if (camera.has("rotationSensitivity"))
                currentCamera.setRotationSensitivity((float) camera.getDouble("rotationSensitivity"));
            if (mInitialPitch != PLConstants.kFloatUndefinedValue)
                pitch = mInitialPitch;
            else if (keep.vLookAt)
                pitch = oldCamera.getLookAtRotation().pitch;
            else if (camera.has("vLookAt"))
                pitch = (float) camera.getDouble("vLookAt");
            if (mInitialYaw != PLConstants.kFloatUndefinedValue)
                yaw = mInitialYaw;
            else if (keep.hLookAt)
                yaw = oldCamera.getLookAtRotation().yaw;
            else if (camera.has("hLookAt"))
                yaw = (float) camera.getDouble("hLookAt");
            currentCamera.setInitialLookAt(pitch, yaw);
            currentCamera.lookAt(pitch, yaw);
            if (keep.zoomLevels)
                currentCamera.setZoomLevels(oldCamera.getZoomLevels());
            else if (camera.has("zoomLevels"))
                currentCamera.setZoomLevels(camera.getInt("zoomLevels"));
            if (keep.fovMin)
                currentCamera.setFovMin(oldCamera.getFovMin());
            else if (camera.has("fovMin"))
                currentCamera.setFovMin((float) camera.getDouble("fovMin"));
            if (keep.fovMax)
                currentCamera.setFovMax(oldCamera.getFovMax());
            else if (camera.has("fovMax"))
                currentCamera.setFovMax((float) camera.getDouble("fovMax"));
            if (keep.fovSensitivity)
                currentCamera.setFovSensitivity(oldCamera.getFovSensitivity());
            else if (camera.has("fovSensitivity"))
                currentCamera.setFovSensitivity((float) camera.getDouble("fovSensitivity"));
            if (keep.fov)
                currentCamera.setFov(oldCamera.getFov());
            else if (camera.has("fov"))
                currentCamera.setFov((float) camera.getDouble("fov"));
            else if (camera.has("fovFactor"))
                currentCamera.setFovFactor((float) camera.getDouble("fovFactor"));
            else if (camera.has("zoomFactor"))
                currentCamera.setZoomFactor((float) camera.getDouble("zoomFactor"));
            else if (camera.has("zoomLevel"))
                currentCamera.setZoomLevel(camera.getInt("zoomLevel"));
        }
    } catch (Throwable e) {
        this.didError(e);
        return false;
    }
    return true;
}
 
Example 15
Source File: Capability8Tests.java    From FROST-Server with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static boolean jsonEqualsWithLinkResolving(JSONObject obj1, JSONObject obj2, String topic) {
    if (obj1 == obj2) {
        return true;
    }
    if (obj1 == null) {
        return false;
    }
    if (obj1.getClass() != obj2.getClass()) {
        return false;
    }
    if (obj1.length() != obj2.length()) {
        return false;
    }
    Iterator iterator = obj1.keys();
    while (iterator.hasNext()) {
        String key = iterator.next().toString();
        if (!obj2.has(key)) {
            return false;
        }
        try {
            Object val1 = obj1.get(key);
            if (val1 == null) {
                return obj2.get(key) == null;
            } else if (val1 instanceof JSONObject) {
                if (!jsonEqualsWithLinkResolving((JSONObject) val1, (JSONObject) obj2.getJSONObject(key), topic)) {
                    return false;
                }
            } else if (val1 instanceof JSONArray) {
                JSONArray arr1 = (JSONArray) val1;
                JSONArray arr2 = obj2.getJSONArray(key);
                if (!jsonEqualsWithLinkResolving(arr1, arr2, topic)) {
                    return false;
                }
            } else if (key.toLowerCase().endsWith("time")) {
                if (!checkTimeEquals(val1.toString(), obj2.get(key).toString())) {
                    return false;
                }
            } else if (topic != null && !topic.isEmpty() && key.endsWith("@iot.navigationLink")) {
                String version = topic.substring(0, topic.indexOf("/"));

                String selfLink1 = obj1.getString("@iot.selfLink");
                URI baseUri1 = URI.create(selfLink1.substring(0, selfLink1.indexOf(version))).resolve(topic);
                String navLink1 = obj1.getString(key);
                String absoluteUri1 = baseUri1.resolve(navLink1).toString();

                String selfLink2 = obj2.getString("@iot.selfLink");
                URI baseUri2 = URI.create(selfLink2.substring(0, selfLink2.indexOf(version))).resolve(topic);
                String navLink2 = obj2.getString(key);
                String absoluteUri2 = baseUri2.resolve(navLink2).toString();
                if (!absoluteUri1.equals(absoluteUri2)) {
                    return false;
                }

            } else if (!val1.equals(obj2.get(key))) {
                return false;
            }
        } catch (JSONException ex) {
            return false;
        }
    }
    return true;
}
 
Example 16
Source File: JSONParser.java    From 1Rramp-Android with MIT License 4 votes vote down vote up
public User parseCoreUserJson(JSONObject userObj) {
  User user = new User();
  try {
    JSONObject jmd = getJsonMetaDataObject(userObj);
    if (jmd.has("profile")) {
      JSONObject po = jmd.getJSONObject("profile");
      user.setProfile_image(po.optString("profile_image", ""));
      user.setCover_image(po.optString("cover_image", ""));
      user.setFullname(po.optString("name", ""));
      user.setLocation(po.optString("location", ""));
      user.setAbout(po.optString("about", ""));
      user.setWebsite(po.optString("website", ""));
    } else {
      user.setProfile_image("");
      user.setCover_image("");
      user.setFullname("");
      user.setLocation("");
      user.setAbout("");
      user.setWebsite("");
    }
    user.setUsername(userObj.getString("name"));
    user.setCreated(userObj.getString("created"));
    user.setCommentCount(userObj.getInt("comment_count"));
    user.setPostCount(userObj.optInt("post_count"));
    user.setCanVote(userObj.getBoolean("can_vote"));
    user.setVotingPower(userObj.getInt("voting_power"));
    user.setReputation(userObj.getLong("reputation"));
    user.setSavings_sbd_balance(userObj.getString("savings_sbd_balance"));
    user.setSbd_balance(userObj.getString("sbd_balance"));
    user.setSavings_balance(userObj.getString("savings_balance"));
    user.setSbdRewardBalance(userObj.getString("reward_sbd_balance"));
    user.setSteemRewardBalance(userObj.getString("reward_steem_balance"));
    user.setVestsRewardBalance(userObj.getString("reward_vesting_balance"));
    user.setReceived_vesting_shares(userObj.getString("received_vesting_shares"));
    user.setDelegated_vesting_shares(userObj.getString("delegated_vesting_shares"));
    user.setBalance(userObj.getString("balance"));
    user.setVesting_share(userObj.getString("vesting_shares"));
  }
  catch (JSONException e) {
    e.printStackTrace();
  }
  return user;
}
 
Example 17
Source File: MeLayout.java    From Makeblock-App-For-Android with MIT License 4 votes vote down vote up
public MeLayout(JSONObject json){
		try {
			name = json.getString("name");
			if(json.has("type")){
				type = json.getInt("type");
			}
			createTime = json.getString("createTime");
			updateTime = json.getString("updateTime");
			JSONArray moduleListJArray = json.getJSONArray("moduleList");
			moduleList = new ArrayList<MeModule>();
			for (int i=0;i<moduleListJArray.length();i++){ 
				JSONObject jobj = (JSONObject) moduleListJArray.get(i);
				
				int modtype = jobj.getInt("type");
				
				MeModule mod=null;
				switch(modtype){
				case MeModule.DEV_ULTRASOINIC:
					mod = new MeUltrasonic(jobj);
					break;
				case MeModule.DEV_TEMPERATURE:
					mod = new MeTemperature(jobj);
					break;
				case MeModule.DEV_LIGHTSENSOR:
					mod = new MeLightSensor(jobj);
					break;
				case MeModule.DEV_SOUNDSENSOR:
					mod = new MeSoundSensor(jobj);
					break;	
				case MeModule.DEV_LINEFOLLOWER:
					mod = new MeLineFollower(jobj);
					break;
				case MeModule.DEV_POTENTIALMETER:
					mod = new MePotential(jobj);
					break;
				case MeModule.DEV_LIMITSWITCH:
					mod = new MeLimitSwitch(jobj);
					break;
				case MeModule.DEV_BUTTON:
					mod = new MeButton(jobj);
					break;
				case MeModule.DEV_PIRMOTION:
					mod = new MePIRSensor(jobj);
					break;
				case MeModule.DEV_DCMOTOR:
					mod = new MeGripper(jobj);
					break;
				case MeModule.DEV_SERVO:
					mod = new MeServoMotor(jobj);
					break;
				case MeModule.DEV_JOYSTICK:
					mod = new MeJoystick(jobj);
					break;
				case MeModule.DEV_RGBLED:
					mod = new MeRgbLed(jobj);
					break;
				case MeModule.DEV_SEVSEG:
					mod = new MeDigiSeg(jobj);
					break;
				case MeModule.DEV_CAR_CONTROLLER:
					mod = new MeCarController(jobj);
					break;

//				case MeModule.DEV_GRIPPER_CONTROLLER:
//					mod = new MeGripper(jobj);
//					break;
				default:
					Log.i(dbg, "unknow module from json "+modtype);
					break;
				}
				if(mod!=null){
					mod.setScaleType(type);
					moduleList.add(mod);
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
Example 18
Source File: TestingServicesImpl.java    From mdw with Apache License 2.0 4 votes vote down vote up
public TestCaseItem getTestCaseItem(String path) throws ServiceException {
    try {
        String assetPath = path.substring(0, path.lastIndexOf('/'));
        String pkg = assetPath.substring(0, assetPath.lastIndexOf('/'));
        String itemName = path.substring(path.lastIndexOf('/') + 1).replace('~', '/');
        String method = null;
        String meth = null;
        int colon = itemName.indexOf(':');
        if (colon > 0) {
            method = meth = itemName.substring(0, colon);
            itemName = itemName.substring(colon + 1);
            if (method.equals("DEL"))
                method = "DELETE";
            else if (method.equals("OPT"))
                method = "OPTIONS";
        }
        AssetInfo testCaseAsset = assetServices.getAsset(assetPath);
        if (testCaseAsset == null)
            throw new ServiceException(ServiceException.NOT_FOUND, "Test case not found: " + assetPath);
        TestCaseItem item = null;
        String json = new String(FileHelper.read(testCaseAsset.getFile()));
        JSONObject coll = new JSONObject(json);
        if (coll.has("item")) {
            JSONArray items = coll.getJSONArray("item");
            for (int i = 0; i < items.length(); i++) {
                JSONObject itemObj = items.getJSONObject(i);
                String itemObjName = itemObj.getString("name");
                if (itemName.equals(itemObjName)) {
                    if (method == null) {
                        item = new TestCaseItem(itemName);
                    }
                    else {
                        if (itemObj.has("request")) {
                            JSONObject request = itemObj.getJSONObject("request");
                            if (request.has("method") && request.getString("method").equals(method))
                                item = new TestCaseItem(itemName);
                        }
                    }
                    if (item != null) {
                        item.setObject(itemObj);
                        break;
                    }
                }
            }
        }
        if (item != null) {
            PackageAssets pkgAssets = assetServices.getAssets(pkg);
            File resultsDir = getTestResultsDir();
            String rootName = item.getName().replace('/', '_');
            if (meth != null)
                rootName = meth + '_' + rootName;
            for (AssetInfo pkgAsset : pkgAssets.getAssets()) {
                if ("yaml".equals(pkgAsset.getExtension()) && pkgAsset.getRootName().equals(rootName)) {
                    item.setExpected(pkg + "/" + pkgAsset.getName());
                    if (resultsDir != null) {
                        if (new File(resultsDir + "/" + pkg + "/" + pkgAsset.getName()).isFile())
                            item.setActual(pkg + "/" + pkgAsset.getName());
                    }
                }
            }
            if (new File(resultsDir + "/" + pkg + "/" + rootName + ".log").isFile())
                item.setExecuteLog(pkg + "/" + rootName + ".log");
        }

        if (item != null)
            addStatusInfo(new TestCase(pkg, testCaseAsset));
        return item;
    }
    catch (Exception ex) {
        throw new ServiceException("IO Error reading test case: " + path, ex);
    }
}
 
Example 19
Source File: FunctionExecutionUtils.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static DataMiningTemplate getDataMiningTemplate(SbiCatalogFunction function) {
	DataMiningTemplate template = null;
	IDataSetDAO dsDAO = null;
	try {
		dsDAO = DAOFactory.getDataSetDAO();

		template = new DataMiningTemplate();
		template.setLanguage(function.getLanguage());

		Set<SbiFunctionInputDataset> datasets = function.getSbiFunctionInputDatasets();
		List<DataMiningDataset> dataminingDatasets = new ArrayList<DataMiningDataset>();
		List<DataMiningFile> dataminingFiles = new ArrayList<DataMiningFile>();

		for (SbiFunctionInputDataset dataset : datasets) {
			DataMiningDataset d = new DataMiningDataset();
			int dsId = dataset.getId().getDsId();
			IDataSet iDataset = dsDAO.loadDataSetById(dsId);
			// Controllo se dataset è di tipo file, del tipo previsto (e.g. csv)
			d.setLabel(iDataset.getLabel());
			d.setSpagobiLabel(iDataset.getLabel());
			d.setCanUpload(true);
			d.setName(iDataset.getName());
			d.setType(DataMiningConstants.DATASET_TYPE_DATASET); // the dataminingEngine differences spagoBI datasets from file datasets created when
																	// executing a document
			JSONObject confObj = new JSONObject(iDataset.getConfiguration());

			if (confObj.has("fileName")) {
				d.setFileName(confObj.getString("fileName"));
				d.setOptions("sep='" + confObj.getString("csvDelimiter") + "'");
				d.setReadType(confObj.getString("fileType").toLowerCase());
			}
			dataminingDatasets.add(d);
		}
		template.setDatasets(dataminingDatasets);

		Set<SbiFunctionInputVariable> variables = function.getSbiFunctionInputVariables();
		Set<SbiFunctionOutput> outputs = function.getSbiFunctionOutputs();
		Set<SbiFunctionInputFile> files = function.getSbiFunctionInputFiles();

		DataMiningCommand c = new DataMiningCommand();
		c.setLabel("CatalogCommand");
		c.setName("CatalogCommand");
		c.setScriptName("CatalogScript");

		List<Variable> vars = new ArrayList<Variable>();
		List<Output> outs = new ArrayList<Output>();

		for (SbiFunctionInputVariable v : variables) {
			Variable var = new Variable();
			var.setName(v.getId().getVarName());
			var.setValue(v.getVarValue());
			vars.add(var);
		}

		for (SbiFunctionInputFile f : files) {
			DataMiningFile file = new DataMiningFile();
			file.setAlias(f.getAlias());
			file.setContent(f.getContent());
			file.setFileName(f.getId().getFileName());
			dataminingFiles.add(file);
		}

		for (SbiFunctionOutput o : outputs) {
			Output out = new Output();
			out.setOuputLabel(o.getId().getLabel());
			out.setOutputName(o.getId().getLabel()); // Name=label
			IDomainDAO domainsDAO = DAOFactory.getDomainDAO();
			String type = domainsDAO.loadDomainById(o.getOutType()).getValueName();
			out.setOutputType(type);
			out.setOutputMode("auto");
			out.setOutputName(o.getId().getLabel());
			out.setOutputValue(o.getId().getLabel());
			outs.add(out);
		}
		c.setVariables(vars);
		c.setOutputs(outs);

		List<DataMiningCommand> commands = new ArrayList<DataMiningCommand>();
		commands.add(c);
		template.setCommands(commands);

		List<DataMiningScript> dataMiningScripts = new ArrayList<DataMiningScript>();
		String scriptCode = function.getScript();
		DataMiningScript script = new DataMiningScript();
		script.setName("CatalogScript");
		script.setCode(scriptCode);
		dataMiningScripts.add(script);
		template.setScripts(dataMiningScripts);
		template.setFiles(dataminingFiles);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return template;
}
 
Example 20
Source File: TagsManager.java    From geopaparazzi with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Utility method to get the formitems of a form object.
 * <p>
 * <p>Note that the entering json object has to be one
 * object of the main array, not THE main array itself,
 * i.e. a choice was already done.
 *
 * @param formObj the single object.
 * @return the array of items of the contained form or <code>null</code> if
 * no form is contained.
 * @throws JSONException if something goes wrong.
 */
public static JSONArray getFormItems(JSONObject formObj) throws JSONException {
    if (formObj.has(TAG_FORMITEMS)) {
        JSONArray formItemsArray = formObj.getJSONArray(TAG_FORMITEMS);
        int emptyIndex = -1;
        while ((emptyIndex = hasEmpty(formItemsArray)) >= 0) {
            formItemsArray.remove(emptyIndex);
        }
        return formItemsArray;
    }
    return new JSONArray();
}