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

The following examples show how to use org.json.JSONObject#getLong() . 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: SochainAPI.java    From cashuwallet with MIT License 6 votes vote down vote up
@Override
public BigInteger getFeeEstimate() {
    try {
        String url1 = baseUrl.replace("*", "get_info");
        JSONObject data1 = new JSONObject(urlFetch(url1));
        data1 = data1.getJSONObject("data");
        long height = data1.getLong("blocks");
        String url2 = baseUrl.replace("*", "block") + "/" + height;
        JSONObject data2 = new JSONObject(urlFetch(url2));
        data2 = data2.getJSONObject("data");
        BigInteger fees = new BigDecimal(data2.getString("fee")).multiply(BigDecimal.TEN.pow(8)).toBigInteger();
        BigInteger size = BigInteger.valueOf(data2.getLong("size"));
        BigInteger fee = fees.multiply(BigInteger.valueOf(1024)).divide(size);
        return fee.max(BigInteger.valueOf(1024));
    } catch (Exception e) {
        return null;
    }
}
 
Example 2
Source File: GameRound.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public GameRound(JSONObject obj) throws JSONException {
    gameId = obj.getString("GameId");
    timestamp = obj.getLong("Timestamp");
    blackCard = new RoundCard(obj.getJSONObject("BlackCard"));

    JSONArray winningPlay = obj.getJSONArray("WinningPlay");
    winningCard = new ArrayList<>(winningPlay.length());
    for (int i = 0; i < winningPlay.length(); i++)
        winningCard.add(new RoundCard(winningPlay.getJSONObject(i)));

    JSONArray otherPlays = obj.getJSONArray("OtherPlays");
    otherCards = new ArrayList<>(otherPlays.length());
    for (int i = 0; i < otherPlays.length(); i++) {
        JSONArray sub = otherPlays.getJSONArray(i);
        List<RoundCard> subCards = new ArrayList<>(sub.length());
        otherCards.add(subCards);
        for (int j = 0; j < sub.length(); j++)
            subCards.add(new RoundCard(sub.getJSONObject(j)));
    }
}
 
Example 3
Source File: PostDataFromSpark.java    From ecosys with Apache License 2.0 6 votes vote down vote up
/**
 * This function checking the response info send back from server
 * whether the upsert request succeed or failed
 *
 * @param responseInfo response information from server
 * @param type upserting vertex or edge
 */
public static Boolean upsertStatus(String responseInfo, String type) {
  try{
    JSONObject obj = new JSONObject(responseInfo);
    if (!obj.has("reports")) {
      return true;
    }
    JSONArray objArray = obj.getJSONArray("reports");
    JSONObject obj1 = objArray.getJSONObject(0);
    JSONObject obj2 = obj1.getJSONObject("statistics");
    long validLine = obj2.getLong("validLine");
    if (validLine == 0) {
      return true;
    }
    JSONArray vertexInfo = obj2.getJSONArray(type);
    long validObject = vertexInfo.getJSONObject(0).getLong("validObject");
    if (validObject == 0) {
      return true;
    }
    return false;
  } catch (Exception e) {
    e.printStackTrace();
  }
  return false;
}
 
Example 4
Source File: AnrFileParser.java    From ArgusAPM with Apache License 2.0 6 votes vote down vote up
/**
 * 判断是否已经上传过
 */
private boolean isUploaded(long pid, long ts) {
    try {
        String recentPidsStr = PreferenceUtils.getString(mContext, PreferenceUtils.SP_KEY_RECENT_PIDS, "");
        if (TextUtils.isEmpty(recentPidsStr)) {
            return false;
        }
        JSONArray jsonArray = new JSONArray(recentPidsStr);
        if (jsonArray != null && jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject recordJson = (JSONObject) jsonArray.get(i);
                long recordPid = recordJson.getLong(JSON_KEY_PID);
                long recordTime = recordJson.getLong(JSON_KEY_TIME);
                if (pid == recordPid && recordTime == ts) {
                    return true;
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 5
Source File: SolrFacetPivotDataReader.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONArray getMissingDocs(String categoryAlias, JSONObject facet) throws JSONException {
	JSONObject missing = facet.getJSONObject("missing");
	long count = missing.getLong("count");
	if (count > 0) {
		Object value = "";
		return getDocs(missing, categoryAlias, value);
	} else {
		return new JSONArray();
	}
}
 
Example 6
Source File: Torrent.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
public Torrent(JSONObject obj) throws JSONException {
    engineId = obj.getString("engine");
    title = obj.getString("title");
    magnet = obj.getString("magnet");
    torrentFileUrl = CommonUtils.optString(obj, "torrent");
    size = obj.getLong("size");
    seeders = obj.getInt("seeders");
    leeches = obj.getInt("leeches");
}
 
Example 7
Source File: EntityAnswer.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
public static EntityAnswer fromJSON(JSONObject json) throws JSONException {
    EntityAnswer answer = new EntityAnswer();
    answer.id = json.getLong("id");
    answer.name = json.getString("name");
    answer.favorite = json.optBoolean("favorite");
    answer.hide = json.optBoolean("hide");
    answer.text = json.getString("text");
    return answer;
}
 
Example 8
Source File: TaskList.java    From mdw with Apache License 2.0 5 votes vote down vote up
public TaskList(String name, JSONObject jsonObj) throws JSONException, ParseException {
    this.name = name;
    if (jsonObj.has("count"))
        count = jsonObj.getInt("count");
    if (jsonObj.has("total"))
        total = jsonObj.getLong("total");
    if (jsonObj.has(name)) {
        JSONArray taskList = jsonObj.getJSONArray(name);
        for (int i = 0; i < taskList.length(); i++)
            tasks.add(new TaskInstance((JSONObject)taskList.get(i)));
    }
}
 
Example 9
Source File: OtpInfo.java    From Aegis with GNU General Public License v3.0 5 votes vote down vote up
public static OtpInfo fromJson(String type, JSONObject obj) throws OtpInfoException {
    OtpInfo info;

    try {
        byte[] secret = Base32.decode(obj.getString("secret"));
        String algo = obj.getString("algo");
        int digits = obj.getInt("digits");

        switch (type) {
            case TotpInfo.ID:
                info = new TotpInfo(secret, algo, digits, obj.getInt("period"));
                break;
            case SteamInfo.ID:
                info = new SteamInfo(secret, algo, digits, obj.getInt("period"));
                break;
            case HotpInfo.ID:
                info = new HotpInfo(secret, algo, digits, obj.getLong("counter"));
                break;
            default:
                throw new OtpInfoException("unsupported otp type: " + type);
        }
    } catch (EncodingException | JSONException e) {
        throw new OtpInfoException(e);
    }

    return info;
}
 
Example 10
Source File: RequestAggregate.java    From mdw with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public RequestAggregate(JSONObject json) throws JSONException {
    value = json.getLong("value");
    if (json.has("count"))
        count = json.getLong("count");
    if (json.has("path"))
        path = json.getString("path");
    else if (json.has("name"))
        path = json.getString("name");
    if (json.has("status"))
        status = json.getInt("status");
}
 
Example 11
Source File: TronscanAPI.java    From cashuwallet with MIT License 5 votes vote down vote up
@Override
public BigInteger getBalance(String address) {
    try {
        String url = baseUrl + "account?address=" + address;
        JSONObject data = new JSONObject(Network.urlFetch(url));
        long balance = data.getLong("balance");
        return BigInteger.valueOf(balance);
    } catch (Exception e) {
        return null;
    }
}
 
Example 12
Source File: JSONHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
public static long getLong(final JSONObject payload, final String key, final long defaultValue) throws JSONException {
	long result = defaultValue;
	if (payload.has(key)) {
		try {
			result = payload.getLong(key);
		} catch (final JSONException e) {
			try {
				result = Long.parseLong(payload.getString(key));
			} catch (final Exception e1) {
				result = payload.getBoolean(key) ? 1 :0;
			}
		}
	}
	return result;
}
 
Example 13
Source File: Combobox.java    From android_maplibui with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void init(JSONObject element,
                 List<Field> fields,
                 Bundle savedState,
                 Cursor featureCursor,
                 SharedPreferences preferences,
                 Map<String, Map<String, String>> translations) throws JSONException{

    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_NAME_KEY);
    mIsShowLast = ControlHelper.isSaveLastValue(attributes);
    setEnabled(ControlHelper.isEnabled(fields, mFieldName));

    String lastValue = null;
    if (ControlHelper.hasKey(savedState, mFieldName))
        lastValue = savedState.getString(ControlHelper.getSavedStateKey(mFieldName));
    else if (null != featureCursor) {
            int column = featureCursor.getColumnIndex(mFieldName);
            if (column >= 0)
                lastValue = featureCursor.getString(column);
    } else if (mIsShowLast)
        lastValue = preferences.getString(mFieldName, null);

    int defaultPosition = 0;
    int lastValuePosition = -1;
    mAliasValueMap = new HashMap<>();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(getContext(), R.layout.formtemplate_spinner);
    setAdapter(spinnerArrayAdapter);

    if (attributes.has(ConstantsUI.JSON_NGW_ID_KEY) && attributes.getLong(ConstantsUI.JSON_NGW_ID_KEY) != -1) {
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        if (null == map)
            throw new IllegalArgumentException("The map should extends MapContentProviderHelper or inherited");

        String account = element.optString(SyncStateContract.Columns.ACCOUNT_NAME);
        long id = attributes.optLong(JSON_NGW_ID_KEY, -1);
        for (int i = 0; i < map.getLayerCount(); i++) {
            if (map.getLayer(i) instanceof NGWLookupTable) {
                NGWLookupTable table = (NGWLookupTable) map.getLayer(i);
                if (table.getRemoteId() != id || !table.getAccountName().equals(account))
                    continue;

                int j = 0;
                for (Map.Entry<String, String> entry : table.getData().entrySet()) {
                    mAliasValueMap.put(entry.getValue(), entry.getKey());

                    if (null != lastValue && lastValue.equals(entry.getKey()))
                        lastValuePosition = j;

                    spinnerArrayAdapter.add(entry.getValue());
                    j++;
                }

                break;
            }
        }
    } else {
        JSONArray values = attributes.optJSONArray(JSON_VALUES_KEY);
        if (values != null) {
            for (int j = 0; j < values.length(); j++) {
                JSONObject keyValue = values.getJSONObject(j);
                String value = keyValue.getString(JSON_VALUE_NAME_KEY);
                String value_alias = keyValue.getString(JSON_VALUE_ALIAS_KEY);

                if (keyValue.has(JSON_DEFAULT_KEY) && keyValue.getBoolean(JSON_DEFAULT_KEY))
                    defaultPosition = j;

                if (null != lastValue && lastValue.equals(value))
                    lastValuePosition = j;

                mAliasValueMap.put(value_alias, value);
                spinnerArrayAdapter.add(value_alias);
            }
        }
    }

    setSelection(lastValuePosition >= 0 ? lastValuePosition : defaultPosition);

    // The drop down view
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    float minHeight = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 14, getResources().getDisplayMetrics());
    setPadding(0, (int) minHeight, 0, (int) minHeight);
}
 
Example 14
Source File: CommandsApi.java    From core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes a POST http request contain AVL data in the message body
 * in JSON format. The data format is:
 * <p>
 * {avl: [{v: "vehicleId1", t: epochTimeMsec, lat: latitude, lon: longitude, 
 *         s:speed(optional), h:heading(optional)},
 *        {v: "vehicleId2", t: epochTimeMsec, lat: latitude, lon: longitude, 
 *         s: speed(optional), h: heading(optional)},
 *        {etc...}
 *        ]
 * }
 * <p>
 * Note: can also specify assignment info using 
 * "assignmentId: 4321, assignmentType: TRIP_ID"
 * where assignmentType can be BLOCK_ID, ROUTE_ID, TRIP_ID, or 
 * TRIP_SHORT_NAME.
 * 
 * @param stdParameters
 * @param requestBody
 * @return ApiCommandAck response indicating whether successful
 * @throws WebApplicationException
 */
@Path("/command/pushAvl")
@POST
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response pushAvlData(@BeanParam StandardParameters stdParameters,
		InputStream requestBody) throws WebApplicationException {
	// Make sure request is valid
	stdParameters.validate();

	Collection<IpcAvl> avlData = new ArrayList<IpcAvl>();
	try {
		// Process the AVL report data from the JSON object
		JSONObject jsonObj = getJsonObject(requestBody);
		JSONArray jsonArray = jsonObj.getJSONArray("avl");
		for (int i = 0; i < jsonArray.length(); ++i) {
			JSONObject avlJsonObj = jsonArray.getJSONObject(i);
			String vehicleId = avlJsonObj.getString("v");
			long time = avlJsonObj.getLong("t");
			double lat = avlJsonObj.getDouble("lat");
			double lon = avlJsonObj.getDouble("lon");
			float speed = avlJsonObj.has("s") ? 
					(float) avlJsonObj.getDouble("s") : Float.NaN;
			float heading = avlJsonObj.has("h") ? 
					(float) avlJsonObj.getDouble("h") : Float.NaN;
					
			// Convert the AVL info into a IpcAvl object to sent to server
			AvlReport avlReport =
					new AvlReport(vehicleId, time, lat, lon, speed,
							heading, AVL_SOURCE);
			
			// Handle assignment info if there is any
			if (avlJsonObj.has("assignmentId")) {
				String assignmentId = avlJsonObj.getString("assignmentId");
				AssignmentType assignmentType = AssignmentType.BLOCK_ID;
				if (avlJsonObj.has("assignmentType")) {
					String assignmentTypeStr =
							avlJsonObj.getString("assignmentType");
					if (assignmentTypeStr.equals("ROUTE_ID"))
						assignmentType = AssignmentType.ROUTE_ID;
					else if (assignmentTypeStr.equals("TRIP_ID"))
						assignmentType = AssignmentType.TRIP_ID;
					else if (assignmentTypeStr.equals("TRIP_SHORT_NAME"))
						assignmentType = AssignmentType.TRIP_SHORT_NAME;
				}
				avlReport.setAssignment(assignmentId, assignmentType);
			}
			
			// Add new IpcAvl report to array of AVL reports to be handled
			avlData.add(new IpcAvl(avlReport));
		}

		// Get RMI interface and send the AVL data to server
		CommandsInterface inter = stdParameters.getCommandsInterface();
		inter.pushAvl(avlData);
	} catch (JSONException | IOException e) {
		// If problem getting data then return a Bad Request
		throw WebUtils.badRequestException(e.getMessage());
	}

	// Create the acknowledgment and return it as JSON or XML
	ApiCommandAck ack = new ApiCommandAck(true, "AVL processed");
	return stdParameters.createResponse(ack);
}
 
Example 15
Source File: ReadPlista.java    From StreamingRec with Apache License 2.0 4 votes vote down vote up
/**
 * This method extracts the information about a user click from a json
 * string
 * 
 * @param jsonstr -
 * @param eventNotification -
 * @return a csv line
 */
private static String readRecommendationRequestOrEventNotification(String jsonstr, boolean eventNotification) {
	//parse the JSON sting to a json object
	JSONObject linejson = new JSONObject(jsonstr);
	// context
	JSONObject contextRR = linejson.getJSONObject("context");
	// each context object contains object of type: simple, lists, cluster
	JSONObject simpleRR = contextRR.getJSONObject("simple");
	JSONObject listRR = contextRR.getJSONObject("lists");

	//create a tmp transaction project (click info + some item metadata 
	//that needs to be merged to item objects later)
	TmpPlistaTransaction transaction = new TmpPlistaTransaction();
	// each list object contains a list of tuples
	// code_11 is Category of the news article
	if (listRR.has("11")) {
		JSONArray categoryArray = listRR.getJSONArray("11");
		if (categoryArray.length() > 1) {
			System.err.println("More than one category.");
		} else if (categoryArray.length() == 1) {
			transaction.category = categoryArray.getInt(0);
		}
	}

	// each simple objects contains a list of tuples
	// code_27 is publisher ID
	if (simpleRR.has("27")) {
		transaction.publisher = simpleRR.getInt("27");
	}

	// code_57 is user cookie
	if (simpleRR.has("57")) {
		transaction.cookie = simpleRR.getLong("57");
	}
	
	// code_25 is item ID
	if (simpleRR.has("25")) {
		transaction.item = new Item();
		transaction.item.id = simpleRR.getLong("25");
	}

	// timestamp
	if (linejson.has("timestamp")) {
		transaction.timestamp = new Date(linejson.getLong("timestamp"));
	}

	// Different branch for event notification
	if (eventNotification) {
		// We dont need to differentiate between event notification and
		// recommendation request right now.
		// But maybe in the future. We can do it here.
	}
	
	JSONObject clustersRR = contextRR.getJSONObject("clusters");
	//keywords
	if (extractText && clustersRR.has("33")) {
		Object object = clustersRR.get("33");
		if(!(object instanceof JSONArray)){
			//replace special line-breaking character 0xAD
			JSONObject keywordObj = (JSONObject) object;
			transaction.keywords = new Object2IntOpenHashMap<>();
			for (String key : keywordObj.keySet()) {
				transaction.keywords.addTo(key.replaceAll(",", " ").replaceAll(Character.toString((char) 0xAD), ""), keywordObj.getInt(key));
			}
		}			
	}

	// create CSV line
	return transaction.toString();
}
 
Example 16
Source File: DriveAnnotationParser.java    From oncokb with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void parseVUS(Gene gene, JSONArray vus, Integer nestLevel) throws JSONException {
        System.out.println(spaceStrByNestLevel(nestLevel) + "Variants of unknown significance");
        if (vus != null) {
            AlterationBo alterationBo = ApplicationContextSingleton.getAlterationBo();
            EvidenceBo evidenceBo = ApplicationContextSingleton.getEvidenceBo();
            AlterationType type = AlterationType.MUTATION; //TODO: cna and fusion

            System.out.println("\t" + vus.length() + " VUSs");
            for (int i = 0; i < vus.length(); i++) {
                JSONObject variant = vus.getJSONObject(i);
                String mutationStr = variant.has("name") ? variant.getString("name") : null;
                JSONObject time = variant.has("time") ? variant.getJSONObject("time") : null;
                Long lastEdit = null;
                if (time != null) {
                    lastEdit = time.has("value") ? time.getLong("value") : null;
                }
//                JSONArray nameComments = variant.has("nameComments") ? variant.getJSONArray("nameComments") : null;
                if (mutationStr != null) {
                    Map<String, String> mutations = parseMutationString(mutationStr);
                    Set<Alteration> alterations = new HashSet<>();
                    for (Map.Entry<String, String> mutation : mutations.entrySet()) {
                        String proteinChange = mutation.getKey();
                        String displayName = mutation.getValue();
                        Alteration alteration = alterationBo.findAlteration(gene, type, proteinChange);
                        if (alteration == null) {
                            alteration = new Alteration();
                            alteration.setGene(gene);
                            alteration.setAlterationType(type);
                            alteration.setAlteration(proteinChange);
                            alteration.setName(displayName);
                            AlterationUtils.annotateAlteration(alteration, proteinChange);
                            alterationBo.save(alteration);
                        }
                        alterations.add(alteration);
                    }

                    Evidence evidence = new Evidence();
                    evidence.setEvidenceType(EvidenceType.VUS);
                    evidence.setGene(gene);
                    evidence.setAlterations(alterations);
                    if (lastEdit != null) {
                        Date date = new Date(lastEdit);
                        evidence.setLastEdit(date);
//                        evidence.setLastReview(date);
                    }
                    if (evidence.getLastEdit() == null) {
                        System.out.println(spaceStrByNestLevel(nestLevel + 1) + "WARNING: " + mutationStr + " do not have last update.");
                    }
                    evidenceBo.save(evidence);
                }
                if (i % 10 == 9)
                    System.out.println("\t\tImported " + (i + 1));
            }
        } else {
            if (vus == null) {
                System.out.println(spaceStrByNestLevel(nestLevel) + "No VUS available.");
            }
        }
    }
 
Example 17
Source File: JMXReader.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
private JMXStatistics getStatistics(String title, String body)
        throws IOException, JSONException {
    JSONObject o = parse(execute(body));
    return (o != null) ? new JMXStatistics((JSONObject) o.get("value"),
            title, o.getLong("timestamp")) : null;
}
 
Example 18
Source File: CreateUpdateTestCaseExecutionFile.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * update action execution with testCaseStepActionJson and all the parameter
 * belonging to it (control)
 *
 * @param JSONObject testCaseJson
 * @param ApplicationContext appContext
 * @throws JSONException
 * @throws IOException
 */
TestCaseStepActionExecution updateTestCaseStepActionExecutionFromJsonArray(JSONArray testCaseStepActionJson, ApplicationContext appContext) throws JSONException, IOException {

    JSONObject currentAction = testCaseStepActionJson.getJSONObject(0);

    long id = currentAction.getLong("id");
    String test = currentAction.getString("test");
    String testCase = currentAction.getString("testcase");
    int step = currentAction.getInt("step");
    int index = currentAction.getInt("index");
    int sort = currentAction.getInt("sort");
    int sequence = currentAction.getInt("sequence");
    String conditionOperator = currentAction.getString("conditionOperator");
    String conditionVal1Init = currentAction.getString("conditionVal1Init");
    String conditionVal2Init = currentAction.getString("conditionVal2Init");
    String conditionVal3Init = currentAction.getString("conditionVal3Init");
    String conditionVal1 = currentAction.getString("conditionVal1");
    String conditionVal2 = currentAction.getString("conditionVal2");
    String conditionVal3 = currentAction.getString("conditionVal3");
    String action = currentAction.getString("action");
    String value1Init = currentAction.getString("value1init");
    String value2Init = currentAction.getString("value2init");
    String value3Init = currentAction.getString("value3init");
    String value1 = currentAction.getString("value1");
    String value2 = currentAction.getString("value2");
    String value3 = currentAction.getString("value3");
    String forceExeStatus = currentAction.getString("forceExeStatus");
    String description = currentAction.getString("description");
    String returnCode = currentAction.getString("returnCode");

    //String wrote by the user
    String returnMessage = StringUtil.sanitize(currentAction.getString("returnMessage"));
    //default message unchanged
    if (returnMessage.equals("Action not executed")) {
        returnMessage = "Action executed manually";
    }

    long start = currentAction.getLong("start");
    long end = currentAction.getLong("end");
    long fullStart = 0;//currentAction.getLong("fullStart");
    long fullEnd = 0;//currentAction.getLong("fullEnd");

    //create this testCaseStepActionExecution and update the bdd with it
    TestCaseStepActionExecution currentTestCaseStepActionExecution = createTestCaseStepActionExecution(id, test, testCase, step, index, sequence, sort, returnCode, returnMessage, conditionOperator, conditionVal1Init, conditionVal2Init, conditionVal3Init, conditionVal1, conditionVal2, conditionVal3, action, value1Init, value2Init, value3Init, value1, value2, value3, forceExeStatus, start, end, fullStart, fullEnd, null, description, null, null);
    return currentTestCaseStepActionExecution;
}
 
Example 19
Source File: DatabaseHelper.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
    try {
        ProfileSwitch profileSwitch = new ProfileSwitch();
        profileSwitch.date = trJson.getLong("mills");
        if (trJson.has("duration"))
            profileSwitch.durationInMinutes = trJson.getInt("duration");
        profileSwitch._id = trJson.getString("_id");
        profileSwitch.profileName = trJson.getString("profile");
        profileSwitch.isCPP = trJson.has("CircadianPercentageProfile");
        profileSwitch.source = Source.NIGHTSCOUT;
        if (trJson.has("timeshift"))
            profileSwitch.timeshift = trJson.getInt("timeshift");
        if (trJson.has("percentage"))
            profileSwitch.percentage = trJson.getInt("percentage");
        if (trJson.has("profileJson"))
            profileSwitch.profileJson = trJson.getString("profileJson");
        else {
            ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
            if (profileInterface != null) {
                ProfileStore store = profileInterface.getProfile();
                if (store != null) {
                    Profile profile = store.getSpecificProfile(profileSwitch.profileName);
                    if (profile != null) {
                        profileSwitch.profileJson = profile.getData().toString();
                        if (L.isEnabled(L.DATABASE))
                            log.debug("Profile switch prefilled with JSON from local store");
                        // Update data in NS
                        NSUpload.updateProfileSwitch(profileSwitch);
                    } else {
                        if (L.isEnabled(L.DATABASE))
                            log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
                        return;
                    }
                } else {
                    if (L.isEnabled(L.DATABASE))
                        log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
                    return;
                }
            } else {
                if (L.isEnabled(L.DATABASE))
                    log.debug("No active profile interface. Ignoring: " + trJson.toString());
                return;
            }
        }
        if (trJson.has("profilePlugin"))
            profileSwitch.profilePlugin = trJson.getString("profilePlugin");
        createOrUpdate(profileSwitch);
    } catch (JSONException e) {
        log.error("Unhandled exception: " + trJson.toString(), e);
    }
}
 
Example 20
Source File: SessionHistory.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 4 votes vote down vote up
public Game(JSONObject obj) throws JSONException {
    id = obj.getString("GameId");
    timestamp = obj.getLong("Timestamp") * 1000;
}