com.google.gson.JsonArray Java Examples

The following examples show how to use com.google.gson.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: KcaUtils.java    From kcanotify_h5-master with GNU General Public License v3.0 7 votes vote down vote up
public static JsonArray getJsonArrayFromStorage(Context context, String name, KcaDBHelper helper) {

        if (getBooleanPreferences(context, PREF_RES_USELOCAL)) {
            return getJsonArrayFromAsset(context, name, helper);
        } else {
            ContextWrapper cw = new ContextWrapper(context);
            File directory = cw.getDir("data", Context.MODE_PRIVATE);
            File jsonFile = new File(directory, name);
            JsonArray data = new JsonArray();
            try {
                Reader reader = new FileReader(jsonFile);
                data = new JsonParser().parse(reader).getAsJsonArray();
                reader.close();
            } catch (IOException | IllegalStateException | JsonSyntaxException e ) {
                e.printStackTrace();
                setPreferences(context, PREF_DATALOAD_ERROR_FLAG, true);
                if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonArrayFromStorage", "0", getStringFromException(e));
                data = getJsonArrayFromAsset(context, name, helper);
            }
            return data;
        }
    }
 
Example #2
Source File: ObservationFromFullInventoryImplementation.java    From malmo with MIT License 7 votes vote down vote up
public static void getInventoryJSON(JsonArray arr, IInventory inventory)
{
    String invName = getInventoryName(inventory);
    for (int i = 0; i < inventory.getSizeInventory(); i++)
    {
        ItemStack is = inventory.getStackInSlot(i);
        if (is != null && !is.isEmpty())
        {
            JsonObject jobj = new JsonObject();
            DrawItem di = MinecraftTypeHelper.getDrawItemFromItemStack(is);
            String name = di.getType();
            if (di.getColour() != null)
                jobj.addProperty("colour", di.getColour().value());
            if (di.getVariant() != null)
                jobj.addProperty("variant", di.getVariant().getValue());
            jobj.addProperty("type", name);
            jobj.addProperty("index", i);
            jobj.addProperty("quantity", is.getCount());
            jobj.addProperty("inventory",  invName);
            arr.add(jobj);
        }
    }
}
 
Example #3
Source File: TestUtils.java    From headlong with Apache License 2.0 6 votes vote down vote up
public static ArrayList<Object> parseArrayToBytesHierarchy(final JsonArray array) {
    ArrayList<Object> arrayList = new ArrayList<>();
    for (JsonElement element : array) {
        if(element.isJsonObject()) {
            arrayList.add(parseObject(element));
        } else if(element.isJsonArray()) {
            arrayList.add(parseArrayToBytesHierarchy(element.getAsJsonArray()));
        } else if(element.isJsonPrimitive()) {
            arrayList.add(parsePrimitiveToBytes(element));
        } else if(element.isJsonNull()) {
            throw new RuntimeException("null??");
        } else {
            throw new RuntimeException("?????");
        }
    }
    return arrayList;
}
 
Example #4
Source File: JsonParserSubjects.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
private List<String> deserializeLocationsFromJsonElement(final JsonElement jsonElement) {
    final JsonArray jsonLocations = jsonElement.getAsJsonArray();
    if (jsonLocations == null) {
        return null;
    }

    // Parse each location:
    final List<String> locations = new ArrayList<>();
    for (final JsonElement jsonLocation : jsonLocations) {
        final JsonObject asObject = jsonLocation.getAsJsonObject();
        final String url = JsonUtils.getString(asObject, "image/jpeg");
        if (url != null) {
            locations.add(url);
        }
    }

    return locations;
}
 
Example #5
Source File: ATLASUtil.java    From Criteria2Query with Apache License 2.0 6 votes vote down vote up
public static List<Concept> searchConceptByName(String entity)
		throws UnsupportedEncodingException, IOException, ClientProtocolException {
	JSONObject queryjson = new JSONObject();
	queryjson.accumulate("QUERY", entity);
	System.out.println("queryjson:" + queryjson);
	String vocabularyresult = getConcept(queryjson);
	System.out.println("vocabularyresult  length=" + vocabularyresult.length());
	Gson gson = new Gson();
	JsonArray ja = new JsonParser().parse(vocabularyresult).getAsJsonArray();
	if (ja.size() == 0) {
		System.out.println("size=" + ja.size());
		return null;
	}
	List<Concept> list = gson.fromJson(ja, new TypeToken<List<Concept>>() {
	}.getType());
	return list;
}
 
Example #6
Source File: UIForms.java    From BedrockConnect with GNU General Public License v3.0 6 votes vote down vote up
public static ModalFormRequestPacket createMain(List<String> servers) {
    currentForm = MAIN;
    ModalFormRequestPacket mf = new ModalFormRequestPacket();
    mf.setFormId(UIForms.MAIN);

    JsonObject out = UIComponents.createForm("form", "Server List");
    out.addProperty("content", "");

    JsonArray buttons = new JsonArray();

    buttons.add(UIComponents.createButton("Connect to a Server"));
    buttons.add(UIComponents.createButton("Remove a Server"));
    for(int i=0;i<servers.size();i++) {
        buttons.add(UIComponents.createButton(servers.get(i), "https://i.imgur.com/3BmFZRE.png", "url"));
    }
    buttons.add(UIComponents.createButton("The Hive", "https://forum.playhive.com/uploads/default/original/1X/0d05e3240037f7592a0f16b11b57c08eba76f19c.png", "url"));
    buttons.add(UIComponents.createButton("Mineplex", "https://www.mineplex.com/assets/www-mp/img/footer/footer_smalllogo.png", "url"));
    buttons.add(UIComponents.createButton("CubeCraft Games", "https://i.imgur.com/aFH1NUr.png", "url"));
    buttons.add(UIComponents.createButton("Lifeboat Network", "https://lbsg.net/wp-content/uploads/2017/06/lifeboat-square.png", "url"));
    buttons.add(UIComponents.createButton("Mineville City", "https://pbs.twimg.com/profile_images/1095835578451537920/0-x9qcw8.png", "url"));
    out.add("buttons", buttons);

    mf.setFormData(out.toString());

    return mf;
}
 
Example #7
Source File: JSONParser.java    From sync-service with Apache License 2.0 6 votes vote down vote up
private JsonObject createGetMetadataResponse(APIGetMetadata response) {
	JsonObject jResponse = new JsonObject();

	if (response.getSuccess()) {
		ItemMetadata metadata = response.getItemMetadata();
		jResponse = parseObjectMetadataForAPI(metadata);

		if (metadata.getChildren() != null) {
			JsonArray contents = new JsonArray();

			for (ItemMetadata entry : metadata.getChildren()) {
				JsonObject entryJson = parseObjectMetadataForAPI(entry);
				contents.add(entryJson);
			}

			jResponse.add("contents", contents);
		}
	} else {
		jResponse.addProperty("error", response.getErrorCode());
		jResponse.addProperty("description", response.getDescription());
	}

	return jResponse;
}
 
Example #8
Source File: Metrics.java    From QuickShop-Reremake with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, Integer> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        JsonArray categoryValues = new JsonArray();
        categoryValues.add(new JsonPrimitive(entry.getValue()));
        values.add(entry.getKey(), categoryValues);
    }
    data.add("values", values);
    return data;
}
 
Example #9
Source File: Metrics.java    From bStats-Metrics with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets the plugin specific data.
 * This method is called using Reflection.
 *
 * @return The plugin specific data.
 */
public JsonObject getPluginData() {
    JsonObject data = new JsonObject();

    String pluginName = plugin.getDescription().getName();
    String pluginVersion = plugin.getDescription().getVersion();

    data.addProperty("pluginName", pluginName);
    data.addProperty("id", pluginId);
    data.addProperty("pluginVersion", pluginVersion);

    JsonArray customCharts = new JsonArray();
    for (CustomChart customChart : charts) {
        // Add the data of the custom charts
        JsonObject chart = customChart.getRequestJsonObject(plugin.getLogger(), logFailedRequests);
        if (chart == null) { // If the chart is null, we skip it
            continue;
        }
        customCharts.add(chart);
    }
    data.add("customCharts", customCharts);

    return data;
}
 
Example #10
Source File: MolecularMatchTrialsObjectFactory.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private static List<MolecularMatchTrialsIntervention> createInterventions(@NotNull JsonArray interventionArray) {
    List<MolecularMatchTrialsIntervention> molecularMatchTrialsInterventionList = Lists.newArrayList();
    ViccDatamodelChecker interventionChecker = ViccDatamodelCheckerFactory.molecularMatchTrialsInterventionChecker();

    for (JsonElement interventionElement : interventionArray) {
        JsonObject interventionObject = interventionElement.getAsJsonObject();
        interventionChecker.check(interventionObject);

        molecularMatchTrialsInterventionList.add(ImmutableMolecularMatchTrialsIntervention.builder()
                .interventionName(optionalString(interventionObject, "intervention_name"))
                .otherNames(optionalStringList(interventionObject, "other_name"))
                .interventionType(optionalString(interventionObject, "intervention_type"))
                .armGroupLabels(optionalStringList(interventionObject, "arm_group_label"))
                .description(optionalString(interventionObject, "description"))
                .build());
    }

    return molecularMatchTrialsInterventionList;
}
 
Example #11
Source File: KcaDeckInfo.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
public String getConditionStatus(JsonArray deckPortData, int deckid) {
    String getConditionInfo = "";
    List<String> conditionList = new ArrayList<String>();
    JsonArray deckShipIdList = (JsonArray) ((JsonObject) deckPortData.get(deckid)).get("api_ship");
    for (int i = 0; i < deckShipIdList.size(); i++) {
        int shipId = deckShipIdList.get(i).getAsInt();
        if (shipId != -1) {
            JsonObject shipData = getUserShipDataById(shipId, "cond");
            int shipCondition = shipData.get("cond").getAsInt();
            conditionList.add(String.valueOf(shipCondition));
        }
    }
    if(conditionList.size() == 0) {
        getConditionInfo = "";
    } else {
        getConditionInfo = joinStr(conditionList, "/");
    }
    return getConditionInfo;

}
 
Example #12
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testMultiParamsParsing_02() {
	Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
	supportedMethods.put("foo", JsonRpcMethod.request("foo",
			new TypeToken<Void>() {}.getType(),
			new TypeToken<String>() {}.getType(),
			new TypeToken<Integer>() {}.getType()));
	MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
	handler.setMethodProvider((id) -> "foo");
	
	RequestMessage message = (RequestMessage) handler.parseMessage("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ "\"params\": [\"foo\", 2],\n"
			+ "\"method\":\"bar\"\n"
			+ "}");
	Assert.assertTrue("" + message.getParams().getClass(), message.getParams() instanceof JsonArray);
}
 
Example #13
Source File: KcaBattle.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
public static void calculateRaigekiDamage(JsonObject damage_info) {
    JsonArray damage_info_fdam = damage_info.getAsJsonArray("api_fdam");
    JsonArray damage_info_edam = damage_info.getAsJsonArray("api_edam");
    for (int i = 0; i < damage_info_fdam.size(); i++) {
        if (isCombinedFleetInSortie() && i >= 6) {
            reduce_value(true, friendCbAfterHps, i - 6, cnv(damage_info_fdam.get(i)), true);
        } else {
            reduce_value(true, friendAfterHps, i, cnv(damage_info_fdam.get(i)), false);
        }
    }
    for (int i = 0; i < damage_info_edam.size(); i++) {
        int value = cnv(damage_info_edam.get(i));
        if (value > 0) {
            if (i < 6) reduce_value(false, enemyAfterHps, i, value, false);
            else reduce_value(false, enemyCbAfterHps, i - 6, value, true);
        }
    }
}
 
Example #14
Source File: KcaBattle.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
public static void calculateFriendSupportFleetHougekiDamage(JsonObject api_data) {
    JsonArray at_eflag = api_data.getAsJsonArray("api_at_eflag");
    JsonArray df_list = api_data.getAsJsonArray("api_df_list");
    JsonArray df_damage = api_data.getAsJsonArray("api_damage");
    for (int i = 0; i < df_list.size(); i++) {
        int eflag = at_eflag.get(i).getAsInt();
        JsonArray target = df_list.get(i).getAsJsonArray();
        JsonArray target_dmg = df_damage.get(i).getAsJsonArray();
        for (int j = 0; j < target.size(); j++) {
            int target_val = cnv(target.get(j));
            int dmg_val = cnv(target_dmg.get(j));
            boolean target_idx_cb = target.get(0).getAsInt() >= 6;
            boolean target_idx_valid = target.get(0).getAsInt() != -1;
            if (eflag == 0) {
                if (target_idx_cb) reduce_value(false, enemyCbAfterHps, target_val - 6, dmg_val, true);
                else if (target_idx_valid) reduce_value(false, enemyAfterHps, target_val, dmg_val, false);
            } else { // Do not count damage for friend fleet
                //if (isCombinedFleetInSortie() && target_idx_cb) reduce_value(true, friendCbAfterHps, target, -6, target_dmg, true);
                //else if (target_idx_valid) reduce_value(true, friendAfterHps, target, target_dmg, false);
            }
        }
    }
}
 
Example #15
Source File: KcaUtils.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
public static JsonArray getJsonArrayFromStorage(Context context, String name, KcaDBHelper helper) {

        if (getBooleanPreferences(context, PREF_RES_USELOCAL)) {
            return getJsonArrayFromAsset(context, name, helper);
        } else {
            ContextWrapper cw = new ContextWrapper(context);
            File directory = cw.getDir("data", Context.MODE_PRIVATE);
            File jsonFile = new File(directory, name);
            JsonArray data = new JsonArray();
            try {
                Reader reader = new FileReader(jsonFile);
                data = new JsonParser().parse(reader).getAsJsonArray();
                reader.close();
            } catch (IOException | IllegalStateException | JsonSyntaxException e ) {
                e.printStackTrace();
                setPreferences(context, PREF_DATALOAD_ERROR_FLAG, true);
                if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonArrayFromStorage", "0", getStringFromException(e));
                data = getJsonArrayFromAsset(context, name, helper);
            }
            return data;
        }
    }
 
Example #16
Source File: DegreeFinalizationCertificate.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
private JsonArray getDegreeFinalizationInfoEntries() {
    if (getDocumentRequest().getDetailed()) {
        JsonArray result = new JsonArray();

        final SortedSet<ICurriculumEntry> entries =
            new TreeSet<ICurriculumEntry>(ICurriculumEntry.COMPARATOR_BY_EXECUTION_PERIOD_AND_NAME_AND_ID);
        entries.addAll(getDocumentRequest().getEntriesToReport());

        final Map<Unit, String> academicUnitIdentifiers = new HashMap<Unit, String>();
        reportEntries(result, entries, academicUnitIdentifiers);

        if (getDocumentRequest().isToShowCredits()) {
            getRemainingCreditsInfoValue(getDocumentRequest().getCurriculum()).ifPresent(value ->{
                getPayload().addProperty("remainingCreditsInfoValue", value);
            });
        }

        if (!academicUnitIdentifiers.isEmpty()) {
            getPayload().add("academicUnitInfoValues", getAcademicUnitInfoValues(academicUnitIdentifiers, getDocumentRequest().getMobilityProgram()));
        }

        return result;
    }
    return null;
}
 
Example #17
Source File: MeshNetworkDeserializer.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns serialized json element containing the groups
 *
 * @param groups Group list
 * @return JsonElement
 */
private JsonElement serializeGroups(@NonNull final List<Group> groups) {
    JsonArray groupsArray = new JsonArray();
    for (Group group : groups) {
        JsonObject groupObj = new JsonObject();
        groupObj.addProperty("name", group.getName());
        if (group.getAddressLabel() == null) {
            groupObj.addProperty("address", MeshAddress.formatAddress(group.getAddress(), false));
        } else {
            groupObj.addProperty("address", MeshParserUtils.uuidToHex(group.getAddressLabel()));
        }
        groupObj.addProperty("parentAddress", MeshAddress.formatAddress(group.getParentAddress(), false));
        groupsArray.add(groupObj);
    }
    return groupsArray;
}
 
Example #18
Source File: Product.java    From EasyVolley with Apache License 2.0 6 votes vote down vote up
public static ArrayList<Product> parseJsonArray(JsonArray jsonArray) {
    ArrayList<Product> products = new ArrayList<>(jsonArray.size());

    Gson gson = new Gson();
    for (int i=0 ; i<jsonArray.size() ; i++) {
        JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
        Product product = gson.fromJson(jsonObject, Product.class);

        // temp hack for build
        for (int j=0 ; j<product.getImages().length ; j++) {
            product.getImages()[j].setPath(product.getImages()[j].getPath().replace("-catalogmobile", ""));
        }

        products.add(product);
    }

    return products;
}
 
Example #19
Source File: TestUtils.java    From Prism4j with Apache License 2.0 6 votes vote down vote up
@NotNull
public static Case readCase(@NotNull String file) {

    final String raw;
    try {
        raw = IOUtils.resourceToString(file, StandardCharsets.UTF_8, TestUtils.class.getClassLoader());
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }

    if (raw == null
            || raw.length() == 0) {
        throw new RuntimeException("Test file has no contents, file: " + file);
    }

    final String[] split = raw.split(DELIMITER);
    if (split.length < 2) {
        throw new RuntimeException("Test file seems to have wrong delimiter, file: " + file);
    }

    final String input = split[0].trim();
    final JsonArray simplifiedOutput = GSON.fromJson(split[1].trim(), JsonArray.class);
    final String description = split[2].trim();

    return new Case(input, simplifiedOutput, description);
}
 
Example #20
Source File: DebugMessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRawMultiParamsParsing_02() {
	Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
	supportedMethods.put("foo", JsonRpcMethod.request("foo",
			new TypeToken<Void>() {}.getType(),
			new TypeToken<String>() {}.getType(),
			new TypeToken<Integer>() {}.getType()));
	DebugMessageJsonHandler handler = new DebugMessageJsonHandler(supportedMethods);
	handler.setMethodProvider((id) -> "foo");

	RequestMessage message = (RequestMessage) handler.parseMessage("{"
			+ "\"seq\":2,\n"
			+ "\"type\":\"request\",\n"
			+ "\"command\":\"bar\",\n"
			+ "\"arguments\": [\"foo\", 2]\n"
			+ "}");
	Assert.assertTrue("" + message.getParams().getClass(), message.getParams() instanceof JsonArray);
}
 
Example #21
Source File: AllocatedSceneRangeDeserializer.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public List<AllocatedSceneRange> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
    final List<AllocatedSceneRange> sceneRanges = new ArrayList<>();
    try {
        final JsonArray jsonObject = json.getAsJsonArray();
        for (int i = 0; i < jsonObject.size(); i++) {
            final JsonObject unicastRangeJson = jsonObject.get(i).getAsJsonObject();
            final int firstScene = Integer.parseInt(unicastRangeJson.get("firstScene").getAsString(), 16);
            final int lastScene = Integer.parseInt(unicastRangeJson.get("lastScene").getAsString(), 16);
            sceneRanges.add(new AllocatedSceneRange(firstScene, lastScene));
        }
    } catch (Exception ex) {
        Log.e(TAG, "Error while de-serializing allocated scene range: " + ex.getMessage());
    }
    return sceneRanges;
}
 
Example #22
Source File: FunctionAppTest.java    From faas-tutorial with Apache License 2.0 6 votes vote down vote up
@Test
public void testFunction() {
    JsonObject args = new JsonObject();
    JsonArray splitStrings = new JsonArray();
    splitStrings.add("apple");
    splitStrings.add("orange");
    splitStrings.add("banana");
    args.add("result", splitStrings);
    JsonObject response = FunctionApp.main(args);
    assertNotNull(response);
    JsonArray results = response.getAsJsonArray("result");
    assertNotNull(results);
    assertEquals(3, results.size());
    List<String> actuals = new ArrayList<>();
    results.forEach(j -> actuals.add(j.getAsString()));
    assertTrue(actuals.contains("APPLE"));
    assertTrue(actuals.contains("ORANGE"));
    assertTrue(actuals.contains("BANANA"));
}
 
Example #23
Source File: StreamingAnalyticsServiceV2.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
@Override
protected List<File> downloadArtifacts(CloseableHttpClient httpclient, JsonArray artifacts) {
    final List<File> files = new ArrayList<>();
    for (JsonElement ae : artifacts) {
        JsonObject artifact = ae.getAsJsonObject();
        if (!artifact.has("download"))
            continue;
        
        String name = jstring(artifact, "name");
        String url = jstring(artifact, "download");
       
        // Don't fail the submit if we fail to download the sab(s).
        try {
            File target = new File(name);
            StreamsRestUtils.getFile(Executor.newInstance(httpclient), getAuthorization(), url, target);
            files.add(target);
        } catch (IOException e) {
            TRACE.warning("Failed to download sab: " + name + " : " + e.getMessage());
        }
    }
    return files;
}
 
Example #24
Source File: DsAPIImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<Circuit> getApartmentCircuits(String sessionToken) {
    String response = transport.execute(
            SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT).addFunction(FunctionKeys.GET_CIRCUITS)
                    .addParameter(ParameterKeys.TOKEN, sessionToken).buildRequestString());

    JsonObject responseObj = JSONResponseHandler.toJsonObject(response);
    if (JSONResponseHandler.checkResponse(responseObj)) {
        responseObj = JSONResponseHandler.getResultJsonObject(responseObj);
        if (responseObj.get(JSONApiResponseKeysEnum.CIRCUITS.getKey()).isJsonArray()) {
            JsonArray array = responseObj.get(JSONApiResponseKeysEnum.CIRCUITS.getKey()).getAsJsonArray();

            List<Circuit> circuitList = new LinkedList<Circuit>();
            for (int i = 0; i < array.size(); i++) {
                if (array.get(i).isJsonObject()) {
                    circuitList.add(new CircuitImpl(array.get(i).getAsJsonObject()));
                }
            }
            return circuitList;
        }
    }
    return new LinkedList<Circuit>();
}
 
Example #25
Source File: LiquidEngineTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static Stream<Arguments> data() throws ParserConfigurationException, SAXException, IOException {
  testdoc = (JsonObject) new com.google.gson.JsonParser().parse(TestingUtilities.loadTestResource("r5", "liquid", "liquid-tests.json"));
  JsonArray tests = testdoc.getAsJsonArray("tests");
  List<Arguments> objects = new ArrayList<>();
  for (JsonElement n : tests) {
    objects.add(Arguments.of(n));
  }
  return objects.stream();
}
 
Example #26
Source File: DefaultNotificationRoomHandler.java    From kurento-room with Apache License 2.0 5 votes vote down vote up
@Override
public void onPublishMedia(ParticipantRequest request, String publisherName, String sdpAnswer,
    Set<UserParticipant> participants, RoomException error) {
  if (error != null) {
    notifService.sendErrorResponse(request, null, error);
    return;
  }
  JsonObject result = new JsonObject();
  result.addProperty(ProtocolElements.PUBLISHVIDEO_SDPANSWER_PARAM, sdpAnswer);
  notifService.sendResponse(request, result);

  JsonObject params = new JsonObject();
  params.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_USER_PARAM, publisherName);
  JsonObject stream = new JsonObject();
  stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_STREAMID_PARAM, "webcam");
  JsonArray streamsArray = new JsonArray();
  streamsArray.add(stream);
  params.add(ProtocolElements.PARTICIPANTPUBLISHED_STREAMS_PARAM, streamsArray);

  for (UserParticipant participant : participants) {
    if (participant.getParticipantId().equals(request.getParticipantId())) {
      continue;
    } else {
      notifService.sendNotification(participant.getParticipantId(),
          ProtocolElements.PARTICIPANTPUBLISHED_METHOD, params);
    }
  }
}
 
Example #27
Source File: JsonElementConversionFactoryTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test
public void schemaWithComplexUnion()
    throws Exception {
  String testName = "schemaWithComplexUnion";
  JsonObject schema = getSchemaData(testName).getAsJsonObject();
  JsonArray expected = getExpectedSchema(testName).getAsJsonArray();

  UnionConverter converter = new UnionConverter(new JsonSchema(schema), state);

  Assert.assertEquals(avroSchemaToJsonElement(converter), expected);
}
 
Example #28
Source File: CiphertextUtils.java    From cerberus with Apache License 2.0 5 votes vote down vote up
/** Convert a ParsedCiphertext in the 'AWS Encryption SDK Message Format' to a JsonObject. */
public static JsonObject toJsonObject(ParsedCiphertext parsedCiphertext) {
  JsonObject o = new JsonObject();
  o.addProperty("version", parsedCiphertext.getVersion());
  o.addProperty("type", parsedCiphertext.getType().toString());
  o.addProperty("cryptoAlgoId", parsedCiphertext.getCryptoAlgoId().toString());
  o.addProperty("messageId", Base64.getEncoder().encodeToString(parsedCiphertext.getMessageId()));
  o.add("encryptionContext", new Gson().toJsonTree(parsedCiphertext.getEncryptionContextMap()));
  o.addProperty("keyBlobCount", parsedCiphertext.getEncryptedKeyBlobCount());
  JsonArray keyBlobs = new JsonArray();
  for (KeyBlob keyBlob : parsedCiphertext.getEncryptedKeyBlobs()) {
    JsonObject blob = new JsonObject();
    blob.addProperty("providerId", keyBlob.getProviderId());
    try {
      blob.addProperty("providerInfo", new String(keyBlob.getProviderInformation(), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      LoggerFactory.getLogger("com.nike.cerberus.util.CiphertextUtils")
          .error("Failed to create new string from key blob provider information", e);
      throw new ApiException(DefaultApiError.INTERNAL_SERVER_ERROR);
    }
    blob.addProperty("isComplete:", keyBlob.isComplete());
    keyBlobs.add(blob);
  }
  o.add("keyBlobs", keyBlobs);
  o.addProperty("contentType", parsedCiphertext.getContentType().toString());
  return o;
}
 
Example #29
Source File: AbstractFeatureSerializer.java    From quaerite with Apache License 2.0 5 votes vote down vote up
static List<Float> toFloatList(JsonElement floatArr) {
    if (floatArr == null) {
        return Collections.emptyList();
    } else if (floatArr.isJsonPrimitive()) {
        return Collections.singletonList(floatArr.getAsFloat());
    } else if (floatArr.isJsonArray()) {
        List<Float> ret = new ArrayList<>();
        for (JsonElement el : ((JsonArray)floatArr)) {
            ret.add(el.getAsJsonPrimitive().getAsFloat());
        }
        return ret;
    } else {
        throw new IllegalArgumentException("Did not expect json object: " + floatArr);
    }
}
 
Example #30
Source File: JsonParser.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void reapComments(JsonObject object, Element context) {
	if (object.has("fhir_comments")) {
		JsonArray arr = object.getAsJsonArray("fhir_comments");
		for (JsonElement e : arr) {
			context.getComments().add(e.getAsString());
		}
	}
}