org.json.JSONArray Java Examples

The following examples show how to use org.json.JSONArray. 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: ReleaseTool.java    From apicurio-studio with Apache License 2.0 9 votes vote down vote up
/**
 * Returns all issues (as JSON nodes) that were closed since the given date.
 * @param since
 * @param githubPAT
 */
private static List<JSONObject> getIssuesForRelease(String since, String githubPAT) throws Exception {
    List<JSONObject> rval = new ArrayList<>();

    String currentPageUrl = "https://api.github.com/repos/apicurio/apicurio-studio/issues";
    int pageNum = 1;
    while (currentPageUrl != null) {
        System.out.println("Querying page " + pageNum + " of issues.");
        HttpResponse<JsonNode> response = Unirest.get(currentPageUrl)
                .queryString("since", since)
                .queryString("state", "closed")
                .header("Accept", "application/json")
                .header("Authorization", "token " + githubPAT).asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to list Issues: " + response.getStatusText());
        }
        JSONArray issueNodes = response.getBody().getArray();
        issueNodes.forEach(issueNode -> {
            JSONObject issue = (JSONObject) issueNode;
            String closedOn = issue.getString("closed_at");
            if (since.compareTo(closedOn) < 0) {
                if (!isIssueExcluded(issue)) {
                    rval.add(issue);
                } else {
                    System.out.println("Skipping issue (excluded): " + issue.getString("title"));
                }
            } else {
                System.out.println("Skipping issue (old release): " + issue.getString("title"));
            }
        });

        System.out.println("Processing page " + pageNum + " of issues.");
        System.out.println("    Found " + issueNodes.length() + " issues on page.");
        String allLinks = response.getHeaders().getFirst("Link");
        Map<String, Link> links = Link.parseAll(allLinks);
        if (links.containsKey("next")) {
            currentPageUrl = links.get("next").getUrl();
        } else {
            currentPageUrl = null;
        }
        pageNum++;
    }

    return rval;
}
 
Example #2
Source File: LeanplumNotificationChannel.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves stored notification channels.
 *
 * @param context The application context.
 * @return List of stored channels or null.
 */
private static List<HashMap<String, Object>> retrieveNotificationChannels(Context context) {
  if (context == null) {
    return null;
  }
  try {
    SharedPreferences preferences = context.getSharedPreferences(Constants.Defaults.LEANPLUM,
        Context.MODE_PRIVATE);
    String jsonChannels = preferences.getString(Constants.Defaults.NOTIFICATION_CHANNELS_KEY,
        null);
    if (jsonChannels == null) {
      return null;
    }
    JSONArray json = new JSONArray(jsonChannels);
    return JsonConverter.listFromJson(json);
  } catch (Exception e) {
    Log.e("Failed to convert notification channels json.");
  }
  return null;
}
 
Example #3
Source File: TestSessionTests.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
private int countTestUsers() {
    TestSession session = getTestSessionWithSharedUser(null);

    String appAccessToken = TestSession.getAppAccessToken();
    assertNotNull(appAccessToken);
    String applicationId = session.getApplicationId();
    assertNotNull(applicationId);

    String fqlQuery = String.format("SELECT id FROM test_account WHERE app_id = %s", applicationId);
    Bundle parameters = new Bundle();
    parameters.putString("q", fqlQuery);
    parameters.putString("access_token", appAccessToken);

    Request request = new Request(null, "fql", parameters, null);
    Response response = request.executeAndWait();

    JSONArray data = (JSONArray) response.getGraphObject().getProperty("data");
    return data.length();
}
 
Example #4
Source File: GRegPublisherLifecycleHistoryTest.java    From product-es with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"wso2.greg", "wso2.greg.es"}, description = "PromoteLifeCycle with fault user",
      dependsOnMethods = {"testPrepareForTestRun"})
public void CheckLCHistory() throws LogViewerLogViewerException, RemoteException,
                                                                  JSONException {
    ClientResponse response = getLifeCycleHistory(assetId, "restservice", lifeCycleName);

    Assert.assertTrue(response.getStatusCode() == 200, "Fault user accepted");

    JSONObject historyObj = new JSONObject(response.getEntity(String.class));
    JSONArray dataObj = historyObj.getJSONArray("data");

    Assert.assertEquals(((JSONObject) ((JSONObject) dataObj.get(0)).getJSONArray("action").
            get(0)).getString("name"), "Demote");
    Assert.assertEquals(((JSONObject) ((JSONObject) dataObj.get(1)).getJSONArray("action").
            get(0)).getString("name"), "Demote");
    Assert.assertEquals(((JSONObject) ((JSONObject) dataObj.get(2)).getJSONArray("action").
            get(0)).getString("name"), "Promote");
    Assert.assertEquals(((JSONObject) ((JSONObject) dataObj.get(3)).getJSONArray("action").
            get(0)).getString("name"), "Promote");

    Assert.assertEquals(dataObj.length(), 8);
}
 
Example #5
Source File: JsonUtils.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the double value from the Json Array for specified index
 * 
 * @param jsonArray The {@link JSONArray} to read the index from
 * @param index The key to read
 * @param required Whether the index is required. If <code>true</code>,
 *            attempting to read it when it is <code>null</code> will throw
 *            a {@link JSONException}
 * @param notNull Whether the value is allowed to be <code>null</code>. If
 *            <code>true</code>, will throw a {@link JSONException} if the
 *            value is null
 * @return The read value
 * @throws JSONException If the double was unable to be read, or if the
 *             required/notNull flags were violated
 */
public static double readDouble(final JSONArray jsonArray, final int index,
                final boolean required, final boolean notNull)
                throws JSONException {

    if (required) {
        //Will throw JsonException if mapping doesn't exist
        return jsonArray.getDouble(index);
    }

    if (notNull && jsonArray.isNull(index)) {
        //throw JsonException because key is null
        throw new JSONException(String.format(Locale.US, NULL_VALUE_FORMAT_ARRAY, index));
    }
    double value = 0.0;
    if (!jsonArray.isNull(index)) {
        value = jsonArray.getDouble(index);
    }
    return value;
}
 
Example #6
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 #7
Source File: VersionMigrator.java    From JetUML with GNU General Public License v3.0 6 votes vote down vote up
private void removeSelfDependencies(JSONObject pDiagram)
{
	JSONArray edges = pDiagram.getJSONArray("edges");
	List<JSONObject> newEdges = new ArrayList<>();
	for( int i = 0; i < edges.length(); i++ )
	{
		JSONObject object = edges.getJSONObject(i);
		if( object.getString("type").equals("DependencyEdge") && object.getInt("start") == object.getInt("end") )
		{
			aMigrated = true; // We don't add the dependency, essentially removing it.
		}
		else
		{
			newEdges.add(object);
		}
	}
	pDiagram.put("edges", new JSONArray(newEdges));
}
 
Example #8
Source File: CalEventInnerData.java    From Easer with GNU General Public License v3.0 6 votes vote down vote up
CalEventInnerData(@NonNull String data, @NonNull PluginDataFormat format, int version) throws IllegalStorageDataException {
    switch (format) {
        default:
            try {
                JSONObject jsonObject = new JSONObject(data);
                this.conditions = new ArraySet<>();
                JSONArray jsonArray_conditions = jsonObject.optJSONArray(T_condition);
                for (int i = 0; i < jsonArray_conditions.length(); i++) {
                    String condition = jsonArray_conditions.getString(i);
                    for (int j = 0; j < condition_name.length; j++) {
                        this.conditions.add(condition);
                    }
                }
            } catch (JSONException e) {
                throw new IllegalStorageDataException(e);
            }
    }
}
 
Example #9
Source File: Deserializer.java    From Klyph with MIT License 6 votes vote down vote up
public List<GraphObject> deserializeArray(JSONArray data)
{
	List<GraphObject> list = new ArrayList<GraphObject>();

	if (data != null)
	{
		int n = data.length();
		for (int i = 0; i < n; i++)
		{
			try
			{
				list.add(deserializeObject(data.getJSONObject(i)));
			}
			catch (JSONException e)
			{}

		}
	}

	return list;
}
 
Example #10
Source File: FlickrFetchr.java    From AndroidProgramming3e with Apache License 2.0 6 votes vote down vote up
private void parseItems(List<GalleryItem> items, JSONObject jsonBody)
        throws IOException, JSONException {

    JSONObject photosJsonObject = jsonBody.getJSONObject("photos");
    JSONArray photoJsonArray = photosJsonObject.getJSONArray("photo");

    for (int i = 0; i < photoJsonArray.length(); i++) {
        JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);

        GalleryItem item = new GalleryItem();
        item.setId(photoJsonObject.getString("id"));
        item.setCaption(photoJsonObject.getString("title"));
        
        if (!photoJsonObject.has("url_s")) {
            continue;
        }
        
        item.setUrl(photoJsonObject.getString("url_s"));
        item.setOwner(photoJsonObject.getString("owner"));
        items.add(item);
    }
}
 
Example #11
Source File: Utility.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
static Map<String, Object> convertJSONObjectToHashMap(JSONObject jsonObject) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    JSONArray keys = jsonObject.names();
    for (int i = 0; i < keys.length(); ++i) {
        String key;
        try {
            key = keys.getString(i);
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                value = convertJSONObjectToHashMap((JSONObject) value);
            }
            map.put(key, value);
        } catch (JSONException e) {
        }
    }
    return map;
}
 
Example #12
Source File: ParseUserData.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected Void doInBackground(Void... voids) {
    try {
        if (!parseFailed) {
            after = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.AFTER_KEY);
            JSONArray children = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
            for (int i = 0; i < children.length(); i++) {
                userDataArrayList.add(parseUserDataBase(children.getJSONObject(i)));
            }
        }
    } catch (JSONException e) {
        parseFailed = true;
        e.printStackTrace();
    }
    return null;
}
 
Example #13
Source File: JsonObject.java    From datamill with ISC License 6 votes vote down vote up
@Override
public byte[] asByteArray() {
    try {
        JSONArray array = object.getJSONArray(name);
        if (array != null) {
            byte[] bytes = new byte[array.length()];
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = (byte) array.getInt(i);
            }

            return bytes;
        }
    } catch (JSONException e) {
        String value = asString();
        if (value != null) {
            return value.getBytes();
        }
    }

    return null;
}
 
Example #14
Source File: WebAppContext.java    From mdw with Apache License 2.0 6 votes vote down vote up
public static String addContextInfo(String str, HttpServletRequest request) {
    try {
        JSONArray inArr = new JSONArray(str);
        JSONArray addedArr = new JSONArray();
        for (int i = 0; i < inArr.length(); i++)
            addedArr.put(inArr.get(i));
        addedArr.put(getContainerInfo(request.getSession().getServletContext()).getJson());
        addedArr.put(getRequestInfo(request).getJson());
        addedArr.put(getSessionInfo(request.getSession()).getJson());
        return addedArr.toString(2);
    }
    catch (Exception ex) {
        LoggerUtil.getStandardLogger().error(ex.getMessage(), ex);
        return str;
    }
}
 
Example #15
Source File: TriggerConnector.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
Trigger fromJSON(String data) {
    try {
        JSONObject d = new JSONObject(data);
        connectorType = Type.valueOf(JsonHelper.safeGetString(d, "connectorType"));
        JSONArray array = d.getJSONArray("triggerList");
        list.clear();
        for (int i = 0; i < array.length(); i++) {
            Trigger newItem = instantiate(new JSONObject(array.getString(i)));
            add(newItem);
        }
    } catch (JSONException e) {
        log.error("Unhandled exception", e);
    }
    return this;
}
 
Example #16
Source File: PercentileMetric.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public PercentileMetric(METRIC_TYPE type, Object val)
{
    this.type = type;
    try
    {
        JSONArray jsonArray = (JSONArray) val;
        Map<String,Number> percentiles = new HashMap<>(jsonArray.length()/2);

        for (int i = 0, length = jsonArray.length(); i < length; i++)
        {
            percentiles.put(jsonArray.getString(i++),jsonArray.getDouble(i));
        }
        value.put(type.toString(), percentiles);
    }
    catch (ClassCastException cce)
    {
        logger.debug("ClassCastException for "+val);
    }
    catch (JSONException e)
    {
        logger.debug("Failed to process percentile for "+val+ " "+e.getMessage());
    }
}
 
Example #17
Source File: MobileContactSingleton.java    From customview-samples with Apache License 2.0 6 votes vote down vote up
/**
 * 将联系人信息列表转成json字符串
 * @param phoneInfoList
 * @return
 */
private String wrapPhoneInfoToContactStr(List<PhoneInfo> phoneInfoList){
    if(phoneInfoList == null || phoneInfoList.size() == 0){
        return "";
    }

    JSONArray jsonArray = new JSONArray();
    for(PhoneInfo phoneInfo: phoneInfoList){
        try {
            JSONObject member = new JSONObject();
            member.put(KEY_PHONE_NUM,phoneInfo.getPhoneNum());
            member.put(KEY_CONTACT_VERSION,phoneInfo.getVersion());
            jsonArray.put(member);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    String result = jsonArray.toString();
    byte[] bytes = result.getBytes();
    Log.d(TAG, "wrapPhoneInfoToContactStr: bytes.length ="+bytes.length);
    return jsonArray.toString();
}
 
Example #18
Source File: EaseAtMessageHelper.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
public boolean isAtMeMsg(EMMessage message){
    EaseUser user = EaseUserUtils.getUserInfo(message.getFrom());
    if(user != null){
        try {
            JSONArray jsonArray = message.getJSONArrayAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG);
            
            for(int i = 0; i < jsonArray.length(); i++){
                String username = jsonArray.getString(i);
                if(username.equals(EMClient.getInstance().getCurrentUser())){
                    return true;
                }
            }
        } catch (Exception e) {
            //perhaps is a @ all message
            String atUsername = message.getStringAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG, null);
            if(atUsername != null){
                if(atUsername.toUpperCase().equals(EaseConstant.MESSAGE_ATTR_VALUE_AT_MSG_ALL)){
                    return true;
                }
            }
            return  false;
        }
        
    }
    return false;
}
 
Example #19
Source File: MarketQueueService.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public Observable<MagicLinkData[]> fetchSalesOrders(String contractAddress) {
    return Single.fromCallable(() -> {
        String result = readFromQueue(contractAddress);

        initParser();

        if (result == null) return new MagicLinkData[0];

        JSONObject stateData = new JSONObject(result);
        JSONArray orders = stateData.getJSONArray("orders");
        MagicLinkData[] trades = new MagicLinkData[orders.length()];

        for (int i = 0; i < orders.length(); i++)
        {
            MagicLinkData data = new MagicLinkData();
            JSONObject order = (JSONObject)orders.get(i);
            data.price = order.getDouble("price");
            data.ticketStart = order.getInt("start");
            int stop = order.getInt("stop");
            data.ticketCount = order.getInt("count");
            data.expiry = order.getLong("expiry");
            String base64Msg = order.getString("message");
            String base64Sig = order.getString("signature");

            data.message = cryptoFunctions.Base64Decode(base64Msg);
            MessageData msgData = parser.readByteMessage(data.message, cryptoFunctions.Base64Decode(base64Sig), data.ticketCount);
            data.priceWei = msgData.priceWei;
            data.indices = msgData.tickets;
            System.arraycopy(msgData.signature, 0, data.signature, 0, 65);
            trades[i] = data;
        }

        return trades;
    }).toObservable();
}
 
Example #20
Source File: jo.java    From letv with Apache License 2.0 5 votes vote down vote up
public static List<JSONObject> a(JSONArray jSONArray) throws JSONException {
    List<JSONObject> arrayList = new ArrayList();
    for (int i = 0; i < jSONArray.length(); i++) {
        arrayList.add((JSONObject) jSONArray.get(i));
    }
    return arrayList;
}
 
Example #21
Source File: Core.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static void onFlag(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, POP3Folder ifolder) throws MessagingException, JSONException {
    // Star/unstar message
    DB db = DB.getInstance(context);

    boolean flagged = jargs.getBoolean(0);
    db.message().setMessageFlagged(message.id, flagged);
}
 
Example #22
Source File: WorkgroupList.java    From mdw with Apache License 2.0 5 votes vote down vote up
public JSONObject getJson() throws JSONException {
    JSONObject json = create();
    json.put("retrieveDate", DateHelper.serviceDateToString(getRetrieveDate()));
    json.put("count", count);
    JSONArray array = new JSONArray();
    if (groups != null) {
        for (Workgroup group : groups)
            array.put(group.getJson());
    }
    json.put("workgroups", array);
    return json;
}
 
Example #23
Source File: Library.java    From coloring with GNU General Public License v3.0 5 votes vote down vote up
public int getNumberPagesFromCurrentBook() {
    try {
        JSONArray pages = currentBook.getJSONArray("pages");
        return pages.length();
    } catch (JSONException e) {
        throw new RuntimeException("library json content problem: retrieving number of pages entries in book", e);
    }
}
 
Example #24
Source File: BackupFileManager.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Deserialize the given byte array to an account map, which essentially just a map from string to string.
 * It returns null at any exception. This function assume the bytes are in json format.
 * @param bytes The byte array to deserialize.
 * @return An account map.
 */
static Map<String, String> deserializeAccountMap(byte[] bytes) {
  try {
    JSONArray array = new JSONArray(new String(bytes, StandardCharsets.UTF_8));
    Map<String, String> result = new HashMap<>();
    for (int i = 0; i < array.length(); i++) {
      Account account = Account.fromJson(array.getJSONObject(i));
      result.put(String.valueOf(account.getId()), array.getJSONObject(i).toString());
    }
    return result;
  } catch (JSONException e) {
    logger.error("Failed to deserialized bytes to account map: {}", e.getMessage());
    return null;
  }
}
 
Example #25
Source File: BundleJSONConverter.java    From react-native-fcm with MIT License 5 votes vote down vote up
public static JSONObject convertToJSON(Bundle bundle) throws JSONException {
    JSONObject json = new JSONObject();

    for(String key : bundle.keySet()) {
        Object value = bundle.get(key);
        if (value == null) {
            // Null is not supported.
            continue;
        }

        // Special case List<String> as getClass would not work, since List is an interface
        if (value instanceof List<?>) {
            JSONArray jsonArray = new JSONArray();
            @SuppressWarnings("unchecked")
            List<String> listValue = (List<String>)value;
            for (String stringValue : listValue) {
                jsonArray.put(stringValue);
            }
            json.put(key, jsonArray);
            continue;
        }

        // Special case Bundle as it's one way, on the return it will be JSONObject
        if (value instanceof Bundle) {
            json.put(key, convertToJSON((Bundle)value));
            continue;
        }

        Setter setter = SETTERS.get(value.getClass());
        if (setter == null) {
            throw new IllegalArgumentException("Unsupported type: " + value.getClass());
        }
        setter.setOnJSON(json, key, value);
    }

    return json;
}
 
Example #26
Source File: WifiManagerSnippet.java    From mobly-bundled-snippets with Apache License 2.0 5 votes vote down vote up
@Rpc(
        description =
                "Get Wi-Fi scan results, which is a list of serialized WifiScanResult objects.")
public JSONArray wifiGetCachedScanResults() throws JSONException {
    JSONArray results = new JSONArray();
    for (ScanResult result : mWifiManager.getScanResults()) {
        results.put(mJsonSerializer.toJson(result));
    }
    return results;
}
 
Example #27
Source File: Vibration.java    From showCaseCordova with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArray of arguments for the plugin.
 * @param callbackContext   The callback context used when calling back into JavaScript.
 * @return                  True when the action was valid, false otherwise.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("vibrate")) {
        this.vibrate(args.getLong(0));
    }
    else if (action.equals("vibrateWithPattern")) {
        JSONArray pattern = args.getJSONArray(0);
        int repeat = args.getInt(1);
        //add a 0 at the beginning of pattern to align with w3c
        long[] patternArray = new long[pattern.length()+1];
        patternArray[0] = 0;
        for (int i = 0; i < pattern.length(); i++) {
            patternArray[i+1] = pattern.getLong(i);
        }
        this.vibrateWithPattern(patternArray, repeat);
    }
    else if (action.equals("cancelVibration")) {
        this.cancelVibration();
    }
    else {
        return false;
    }

    // Only alert and confirm are async.
    callbackContext.success();

    return true;
}
 
Example #28
Source File: RuleServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void checkRuleComplete(JSONObject result) throws Exception
{
    assertNotNull("Response is null.", result);

    // if id present in response -> rule was created
    assertTrue(result.has("id"));

    assertEquals(result.getString("title"), "test_rule");
    assertEquals(result.getString("description"), "this is description for test_rule");

    JSONArray ruleType = result.getJSONArray("ruleType");

    assertEquals(1, ruleType.length());
    assertEquals("outbound", ruleType.getString(0));

    assertTrue(result.getBoolean("applyToChildren"));
    assertFalse(result.getBoolean("executeAsynchronously"));
    assertFalse(result.getBoolean("disabled"));
    assertTrue(result.has("owningNode"));
    JSONObject owningNode = result.getJSONObject("owningNode");
    assertTrue(owningNode.has("nodeRef"));
    assertTrue(owningNode.has("name"));
    assertTrue(result.has("url"));

    JSONObject jsonAction = result.getJSONObject("action");

    assertTrue(jsonAction.has("id"));

    assertEquals(jsonAction.getString("actionDefinitionName"), "composite-action");
    assertEquals(jsonAction.getString("description"), "this is description for composite-action");
    assertEquals(jsonAction.getString("title"), "test_title");

    assertTrue(jsonAction.getBoolean("executeAsync"));

    assertTrue(jsonAction.has("actions"));
    assertTrue(jsonAction.has("conditions"));
    assertTrue(jsonAction.has("compensatingAction"));
    assertTrue(jsonAction.has("url"));
}
 
Example #29
Source File: CMoveServiceTest.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 5 votes vote down vote up
@Test
public void testCMoveService_cancel() throws Exception {
  basicCMoveServiceTest(
      new TestUtils.DicomWebClientTestBase() {
        @Override
        public JSONArray qidoRs(String path) throws DicomWebException {
          JSONArray instances = new JSONArray();
          instances.put(TestUtils.dummyQidorsInstance());
          return instances;
        }
      },
      () -> new ICStoreSender() {
        @Override
        public long cstore(AetDictionary.Aet target, String studyUid, String seriesUid,
            String sopInstanceUid, String sopClassUid)
            throws IDicomWebClient.DicomWebException, IOException, InterruptedException {
          throw new InterruptedException();
        }

        @Override
        public void close() throws IOException {

        }
      }
      , Status.Cancel
      , moveDestinationAET);
}
 
Example #30
Source File: ObjectMapper.java    From Dream-Catcher with MIT License 5 votes vote down vote up
private JSONArray convertListToJsonArray(Object value)
    throws InvocationTargetException, IllegalAccessException {
  JSONArray array = new JSONArray();
  List<Object> list = (List<Object>) value;
  for(Object obj : list) {
    // Send null, if this is an array of arrays we are screwed
    array.put(obj != null ? getJsonValue(obj, obj.getClass(), null /* field */) : null);
  }
  return array;
}