Java Code Examples for com.google.gson.internal.LinkedTreeMap

The following are top voted examples for showing how to use com.google.gson.internal.LinkedTreeMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: janos   File: DataSourceProcessorTest.java   View source code 7 votes vote down vote up
@Test
public void readOptimizedFilter() throws Exception {
  GetEntitySetUriInfo uriInfo = createMockedUriInfo("Rooms");
  Edm edm = EdmMock.createMockEdm();

  FilterExpression exp = UriParserImpl.parseFilter(edm, edm.getEntityType("RefScenario", "Room"), "Version gt 105");
  Mockito.when(uriInfo.getFilter()).thenReturn(exp);

  List<Room> results = createRooms(1, 10);
  ReadResult<Room> readResult = ReadResult.forResult(results).filterApplied().build();
  Mockito.when(mockedDataSource.readData(Mockito.any(EdmEntitySet.class), Mockito.any(ReadOptions.class)))
      .thenReturn((ReadResult)readResult);

  ODataResponse result = dataSourceProcessor.readEntitySet(uriInfo, "application/json");

  StringHelper.Stream resultStream = StringHelper.toStream(result.getEntityAsStream());
  List<LinkedTreeMap<?, ?>> parsedResults = JsonHelper.getResults(resultStream.asString());
  Assert.assertEquals(10, parsedResults.size());
  Assert.assertEquals("Room with id: 1", parsedResults.get(0).get("Name"));
  Assert.assertEquals("Room with id: 9", parsedResults.get(9).get("Name"));
}
 
Example 2
Project: synthea_java   File: Hospital.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static void loadHospitals() {
  String filename = "geography/healthcare_facilities.json";

  try {
    String json = Utilities.readResource(filename);
    Gson g = new Gson();
    HashMap<String, LinkedTreeMap> gson = g.fromJson(json, HashMap.class);
    for (Entry<String, LinkedTreeMap> entry : gson.entrySet()) {
      LinkedTreeMap value = entry.getValue();
      String resourceID = UUID.randomUUID().toString();
      value.put("resourceID", resourceID);
      Hospital h = new Hospital(value);
      hospitalList.add(h);
    }
  } catch (Exception e) {
    System.err.println("ERROR: unable to load json: " + filename);
    e.printStackTrace();
    throw new ExceptionInInitializerError(e);
  }
}
 
Example 3
Project: omero-ms-queue   File: TextAnnotationListTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void deserializesMapsDueToTypeErasure() {
    List<TextAnnotation> initialValue = Collections.singletonList(anno("n", "t"));
    Class<List<TextAnnotation>> valueType = (Class<List<TextAnnotation>>) 
                                            initialValue.getClass();
    List<TextAnnotation> readValue = writeThenRead(initialValue, valueType);
    
    assertThat(readValue, is(not(initialValue)));
    
    LinkedTreeMap<String, LinkedTreeMap<String, String>> deserialized =
            new LinkedTreeMap<>();
    LinkedTreeMap<String, String> deserializedAnno =
            new LinkedTreeMap<>();
    deserializedAnno.put("fst", "n");
    deserializedAnno.put("snd", "t");
    deserialized.put("wrappedValue", deserializedAnno);
    
    assertThat(readValue, is(Collections.singletonList(deserialized)));  // (*)
}
 
Example 4
Project: omero-ms-queue   File: PositiveNListTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void deserializesMapsDueToTypeErasure() {
    List<PositiveN> initialValue = Collections.singletonList(posN(1));
    Class<List<PositiveN>> valueType = (Class<List<PositiveN>>) 
                                            initialValue.getClass();
    List<PositiveN> readValue = writeThenRead(initialValue, valueType);
    
    assertThat(readValue, is(not(initialValue)));
    
    LinkedTreeMap<String, Double> deserialized =
            new LinkedTreeMap<>();
    deserialized.put("wrappedValue", 1.0);
    
    assertThat(readValue, is(Collections.singletonList(deserialized)));  // (*)
}
 
Example 5
Project: logistimo-web-service   File: AssetUtil.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String, String> constructDeviceMetaDataFromJSON(String parentKey,
                                                                  Map<String, Object> result) {
  Map<String, String> metaDataMap = new HashMap<>(1);
  String currentKey;
  for (String key : result.keySet()) {
    Object object = result.get(key);
    currentKey = key;
    if (parentKey != null) {
      currentKey = parentKey + "." + key;
    }
    if (object != null) {
      if (object instanceof LinkedTreeMap) {
        metaDataMap.putAll(constructDeviceMetaDataFromJSON(currentKey, (LinkedTreeMap) object));
      } else {
        metaDataMap.put(currentKey, object.toString());
      }
    }
  }
  return metaDataMap;
}
 
Example 6
Project: bittrex4j   File: BittrexExchangeTest.java   View source code 6 votes vote down vote up
@Test
public void shouldParseUpdateSummaryState() throws IOException{

    bittrexExchange.connectToWebSocket(() -> System.out.println("Connected"));

    verify(mockHubProxy).on(eq("updateSummaryState"),subscriptionHandlerArgumentCaptor.capture(),eq(Object.class));

    bittrexExchange.onUpdateSummaryState(exchangeSummaryState -> {
        assertThat(exchangeSummaryState.getNounce(), equalTo(24724L));
        assertThat(exchangeSummaryState.getDeltas().length, equalTo(56));
        lambdaCalled=true;
    });

    subscriptionHandlerArgumentCaptor.getValue().run(new Gson().fromJson(loadTestResourceAsString("/UpdateSummaryState.json"),LinkedTreeMap.class));
    assertThat(lambdaCalled,is(true));
}
 
Example 7
Project: java-cloudant   File: ResourceServlet.java   View source code 6 votes vote down vote up
private JsonArray getAttachmentList(LinkedTreeMap<String, Object> attachmentList, String docID) {
	JsonArray attachmentArray = new JsonArray();

	for (Object key : attachmentList.keySet()) {
		LinkedTreeMap<String, Object> attach = (LinkedTreeMap<String, Object>) attachmentList.get(key);

		JsonObject attachedObject = new JsonObject();
		// set the content type of the attachment
		attachedObject.addProperty("content_type", attach.get("content_type").toString());
		// append the document id and attachment key to the URL
		attachedObject.addProperty("url", "attach?id=" + docID + "&key=" + key);
		// set the key of the attachment
		attachedObject.addProperty("key", key + "");

		// add the attachment object to the array
		attachmentArray.add(attachedObject);
	}

	return attachmentArray;
}
 
Example 8
Project: popcorn-android   File: HaruProvider.java   View source code 6 votes vote down vote up
public ArrayList<Media> formatListForPopcorn(ArrayList<Media> existingList) {
    for (LinkedTreeMap<String, Object> item : showsList) {
        Media media;
        if (item.get("type").toString().equalsIgnoreCase("movie")) {
            media = new Movie(sMediaProvider, null);
        } else {
            media = new Show(sMediaProvider, null);
        }

        media.title = (String) item.get("name");
        media.videoId = item.get("id").toString();
        media.imdbId = "mal-" + media.videoId;
        String year = item.get("aired").toString();
        if (year.contains(", ")) {
            year = year.split(", ")[1];
        }
        if (year.contains(" ")) {
            year = year.split(" ")[0];
        }
        media.year = year;
        media.image = media.headerImage = item.get("malimg").toString();

        existingList.add(media);
    }
    return existingList;
}
 
Example 9
Project: popcorn-android   File: EZTVProvider.java   View source code 6 votes vote down vote up
public ArrayList<Media> formatListForPopcorn(ArrayList<Media> existingList) {
    for (LinkedTreeMap<String, Object> item : showsList) {
        Show show = new Show(sMediaProvider, sSubsProvider);

        show.title = (String) item.get("title");
        show.videoId = (String) item.get("imdb_id");
        show.seasons = (Integer) item.get("seasons");
        show.tvdbId = (String) item.get("tvdb_id");
        show.year = (String) item.get("year");
        LinkedTreeMap<String, String> images = (LinkedTreeMap<String, String>) item.get("images");
        if(!images.get("poster").contains("images/posterholder.png"))
            show.image = images.get("poster").replace("/original/", "/medium/");
        if(!images.get("poster").contains("images/posterholder.png"))
            show.headerImage = images.get("fanart").replace("/original/", "/medium/");

        existingList.add(show);
    }
    return existingList;
}
 
Example 10
Project: Mskyblock   File: DataBase.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public DataBase(Main plugin) {
	this.plugin = plugin;
	
	plugin.getDataFolder().mkdirs();
	initMessage();
	initDB();
	
	registerCommands();
	
	Skyblock.skyblocklist = new LinkedHashMap<String, Skyblock>();
	Skyblock.plugin = plugin;
	for (Entry<String, Object> v1 : skyblockDB.entrySet()) {
		String player = v1.getKey();
		LinkedTreeMap<String, Object> shares = (LinkedTreeMap<String, Object>) ((LinkedTreeMap<String, Object>)v1.getValue()).get("shares");
		int num = Skyblock.getInt((double)((LinkedTreeMap<String, Object>)v1.getValue()).get("num"));
		Position spawn = stringToPos((String)((LinkedTreeMap<String, Object>)v1.getValue()).get("spawn"));
		LinkedTreeMap<String, Object> invites = (LinkedTreeMap<String, Object>) ((LinkedTreeMap<String, Object>)v1.getValue()).get("invites");
		boolean isInviteAll = (boolean) ((LinkedTreeMap<String, Object>)v1.getValue()).getOrDefault("inviteAll", false);
		boolean pvp = (boolean) ((LinkedTreeMap<String, Object>)v1.getValue()).getOrDefault("pvp", false);
		Skyblock.skyblocklist.put(player, new Skyblock(player, shares, invites, num, spawn, isInviteAll, pvp));
	}
	if (instance == null) {
		instance = this;
	}
}
 
Example 11
Project: alfresco-client-sdk   File: NodeBodyUpdate.java   View source code 6 votes vote down vote up
public NodeBodyUpdate(String name, String nodeType, LinkedTreeMap<String, Object> properties,
        List<String> aspectNames)
{
    this.name = name;
    this.nodeType = nodeType;
    if (properties != null && !properties.isEmpty())
    {
        this.properties = properties;
    }
    else
    {
        this.properties = null;
    }
    this.aspectNames = aspectNames;
    this.permissions = null;
}
 
Example 12
Project: alfresco-client-sdk   File: NodeBodyUpdate.java   View source code 6 votes vote down vote up
public NodeBodyUpdate(String name, String nodeType, LinkedTreeMap<String, Object> properties,
        List<String> aspectNames, PermissionsBodyUpdate permissions)
{
    this.name = name;
    this.nodeType = nodeType;
    if (properties != null && !properties.isEmpty())
    {
        this.properties = properties;
    }
    else
    {
        this.properties = null;
    }
    this.aspectNames = aspectNames;
    this.permissions = permissions;
}
 
Example 13
Project: mobile-messaging-sdk-android   File: JsonSerializerTest.java   View source code 6 votes vote down vote up
@Test
public void execute_JSON_to_Map() throws Exception {
    String json =
            "{" +
                "\"string\":\"String\"," +
                "\"boolean\":true," +
                "\"double\":1.0" +
            "}";

    Map<?,?> jsonMap = new JsonSerializer().deserialize(json, Map.class);
    Map<String, Object> map = new LinkedTreeMap<>();
    assertEquals(map.getClass(), jsonMap.getClass());

    map = (Map<String, Object>)jsonMap;
    Assert.assertTrue(getMessageForClassMismatch(String.class, map.get("string").getClass()), map.get("string") instanceof String);
    Assert.assertTrue(getMessageForClassMismatch(Boolean.class, map.get("boolean").getClass()), map.get("boolean") instanceof Boolean);
    Assert.assertTrue(getMessageForClassMismatch(Double.class, map.get("double").getClass()), map.get("double") instanceof Double);
}
 
Example 14
Project: android-net   File: Message.java   View source code 6 votes vote down vote up
@Nullable
public Coordinate coord() {
  try {
    if (data == null) return null;
    Object locObj = data.get("location");
    if (!(locObj instanceof LinkedTreeMap)) return null;
    //noinspection unchecked
    Object coordObj = ((LinkedTreeMap<String, Object>) locObj).get("coordinates");
    Object[] coords;
    if (coordObj instanceof Collection) {
      coords = ((Collection) coordObj).toArray();
    } else if (coordObj instanceof Object[]) {
      coords = (Object[]) coordObj;
    } else {
      return null;
    }
    return Coordinate.builder()
        .lat(((Number) coords[1]).floatValue())
        .lon(((Number) coords[0]).floatValue())
        .build();
  } catch (Exception ignored) {
  }
  return null;
}
 
Example 15
Project: android-net   File: Message.java   View source code 6 votes vote down vote up
@NonNull
private static JSONObject convertLinkedTreeMapToJSON(LinkedTreeMap<String, Object> ltm) {
  JSONObject jo = new JSONObject();
  Object[] objs = ltm.entrySet().toArray();
  for (Object obj : objs) {
    Map.Entry o = (Map.Entry) obj;
    try {
      if (o.getValue() instanceof LinkedTreeMap) {
        //noinspection unchecked
        jo.put(o.getKey().toString(),
            convertLinkedTreeMapToJSON((LinkedTreeMap<String, Object>) o.getValue()));
      } else {
        jo.put(o.getKey().toString(), o.getValue());
      }
    } catch (JSONException ignored) {
    }
  }
  return jo;
}
 
Example 16
Project: android-net   File: Snapshot.java   View source code 6 votes vote down vote up
@Nullable
public Coordinate coord() {
  try {
    if (data == null) return null;
    Object locObj = data.get("location");
    if (!(locObj instanceof LinkedTreeMap)) return null;
    //noinspection unchecked
    Object coordObj = ((LinkedTreeMap<String, Object>) locObj).get("coordinates");
    Object[] coords;
    if (coordObj instanceof Collection) {
      coords = ((Collection) coordObj).toArray();
    } else if (coordObj instanceof Object[]) {
      coords = (Object[]) coordObj;
    } else {
      return null;
    }
    return Coordinate.builder()
        .lat(((Number) coords[1]).floatValue())
        .lon(((Number) coords[0]).floatValue())
        .build();
  } catch (Exception ignored) {
  }
  return null;
}
 
Example 17
Project: android-net   File: Snapshot.java   View source code 6 votes vote down vote up
@NonNull
private static JSONObject convertLinkedTreeMapToJSON(LinkedTreeMap<String, Object> ltm) {
  JSONObject jo = new JSONObject();
  Object[] objs = ltm.entrySet().toArray();
  for (Object obj : objs) {
    Map.Entry o = (Map.Entry) obj;
    try {
      if (o.getValue() instanceof LinkedTreeMap) {
        //noinspection unchecked
        jo.put(o.getKey().toString(),
            convertLinkedTreeMapToJSON((LinkedTreeMap<String, Object>) o.getValue()));
      } else {
        jo.put(o.getKey().toString(), o.getValue());
      }
    } catch (JSONException ignored) {
    }
  }
  return jo;
}
 
Example 18
Project: android-net   File: StreamMessage.java   View source code 6 votes vote down vote up
@Nullable
public Coordinate coord() {
  try {
    if (payload == null || payload.data == null) return null;
    Object locObj = payload.data.get("location");
    if (!(locObj instanceof LinkedTreeMap)) return null;
    //noinspection unchecked
    Object coordObj = ((LinkedTreeMap<String, Object>) locObj).get("coordinates");
    Object[] coords;
    if (coordObj instanceof Collection) {
      coords = ((Collection) coordObj).toArray();
    } else if (coordObj instanceof Object[]) {
      coords = (Object[]) coordObj;
    } else {
      return null;
    }
    return Coordinate.builder() //
        .lat(((Number) coords[1]).floatValue()) //
        .lon(((Number) coords[0]).floatValue()) //
        .build();
  } catch (Exception ignored) {
  }
  return null;
}
 
Example 19
Project: android-net   File: StreamMessage.java   View source code 6 votes vote down vote up
@NonNull
private static JSONObject convertLinkedTreeMapToJSON(LinkedTreeMap<String, Object> ltm) {
  JSONObject jo = new JSONObject();
  Object[] objs = ltm.entrySet().toArray();
  for (Object obj : objs) {
    Map.Entry o = (Map.Entry) obj;
    try {
      if (o.getValue() instanceof LinkedTreeMap) {
        //noinspection unchecked
        jo.put(o.getKey().toString(),
            convertLinkedTreeMapToJSON((LinkedTreeMap<String, Object>) o.getValue()));
      } else {
        jo.put(o.getKey().toString(), o.getValue());
      }
    } catch (JSONException ignored) {
    }
  }
  return jo;
}
 
Example 20
Project: che   File: PHPUnitTestEngine.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean hasComposerRunner(String projectPath) {
  if (!Files.exists(projectsRoot.resolve(projectPath + "/composer.json"))) {
    return false;
  }

  try (InputStream inputStream =
          Files.newInputStream(projectsRoot.resolve(projectPath + "/composer.json"));
      InputStreamReader reader = new InputStreamReader(inputStream)) {
    Gson gson = new GsonBuilder().create();
    Map<String, ?> composerJsonMap = gson.fromJson(reader, LinkedTreeMap.class);
    Map<String, String> requireDev = (Map<String, String>) composerJsonMap.get("require-dev");
    if (requireDev != null && requireDev.get("phpunit/phpunit") != null) {
      return true;
    }
    Map<String, String> require = (Map<String, String>) composerJsonMap.get("require");
    if (require != null && require.get("phpunit/phpunit") != null) {
      return true;
    }
  } catch (Exception e) {
    LOG.error(e.getMessage(), e);
  }
  return false;
}
 
Example 21
Project: easIE   File: JSONConfigurationDeserializer.java   View source code 6 votes vote down vote up
private ArrayList<ScrapableField> transform_CompanyInfo(ArrayList<ScrapableField> company_info) {
    if (company_info != null) {

        for (int i = 0; i < company_info.size(); i++) {
            Object label = company_info.get(i).label;
            Object value = company_info.get(i).value;

            if (!(label instanceof String)) {
                ExtractionProperties label_value = new Gson().fromJson(
                        (new JSONObject((LinkedTreeMap) label)).toString(),
                        new TypeToken<ExtractionProperties>() {
                }.getType());
                company_info.get(i).setLabel(label_value);
            }

            if (!(value instanceof String)) {
                ExtractionProperties value_value = new Gson().fromJson(
                        (new JSONObject((LinkedTreeMap) value)).toString(),
                        new TypeToken<ExtractionProperties>() {
                }.getType());
                company_info.get(i).setValue(value_value);
            }
        }
    }
    return company_info;
}
 
Example 22
Project: telekom-workflow-engine   File: JsonUtil.java   View source code 6 votes vote down vote up
private static Map<String, Field> getFieldMap( Class<?> clazz ){
    Map<String, Field> fields = new LinkedTreeMap<String, Field>();
    Class<?> current = clazz;
    String prefix = "";
    while( !Object.class.equals( current ) ){
        for( Field field : current.getDeclaredFields() ){
            if( Modifier.isStatic( field.getModifiers() ) && Modifier.isFinal( field.getModifiers() ) ){
                // ignore STATIC FINAL fields
                continue;
            }
            fields.put( prefix + field.getName(), field );
        }
        current = current.getSuperclass();
        prefix = prefix + "super.";
    }
    return fields;
}
 
Example 23
Project: ome-smuggler   File: TextAnnotationListTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void deserializesMapsDueToTypeErasure() {
    List<TextAnnotation> initialValue = Collections.singletonList(anno("n", "t"));
    Class<List<TextAnnotation>> valueType = (Class<List<TextAnnotation>>) 
                                            initialValue.getClass();
    List<TextAnnotation> readValue = writeThenRead(initialValue, valueType);
    
    assertThat(readValue, is(not(initialValue)));
    
    LinkedTreeMap<String, LinkedTreeMap<String, String>> deserialized =
            new LinkedTreeMap<>();
    LinkedTreeMap<String, String> deserializedAnno =
            new LinkedTreeMap<>();
    deserializedAnno.put("fst", "n");
    deserializedAnno.put("snd", "t");
    deserialized.put("wrappedValue", deserializedAnno);
    
    assertThat(readValue, is(Collections.singletonList(deserialized)));  // (*)
}
 
Example 24
Project: ome-smuggler   File: PositiveNListTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void deserializesMapsDueToTypeErasure() {
    List<PositiveN> initialValue = Collections.singletonList(posN(1));
    Class<List<PositiveN>> valueType = (Class<List<PositiveN>>) 
                                            initialValue.getClass();
    List<PositiveN> readValue = writeThenRead(initialValue, valueType);
    
    assertThat(readValue, is(not(initialValue)));
    
    LinkedTreeMap<String, Double> deserialized =
            new LinkedTreeMap<>();
    deserialized.put("wrappedValue", 1.0);
    
    assertThat(readValue, is(Collections.singletonList(deserialized)));  // (*)
}
 
Example 25
Project: crm-mobilesdk-library-for-android   File: Utils.java   View source code 6 votes vote down vote up
public static Object parseAttribute(LinkedTreeMap<String, Object> treeMap) {
        Gson gson = new Gson();

        String[] type = ((LinkedTreeMap) treeMap.get("__metadata")).get("type").toString().split("\\.");
        switch (type[type.length - 1]) {
            case "OptionSetValue":
                return gson.fromJson(gson.toJson(treeMap), OptionSetValue.class);
            case "Money":
                return gson.fromJson(gson.toJson(treeMap), Money.class);
            case "EntityReference":
                return gson.fromJson(gson.toJson(treeMap), EntityReference.class);
            case "EntityCollection":
//                return EntityCollection.loadFromJson(treeMap);
            default:
                return null;
        }

    }
 
Example 26
Project: janos   File: DataSourceProcessorTest.java   View source code 6 votes vote down vote up
@Test
public void readOrder() throws Exception {
  GetEntitySetUriInfo uriInfo = createMockedUriInfo("Rooms");
  Edm edm = EdmMock.createMockEdm();

  OrderByExpression exp = UriParserImpl.parseOrderBy(edm, edm.getEntityType("RefScenario", "Room"), "Name");
  Mockito.when(uriInfo.getOrderBy()).thenReturn(exp);

  List<Room> results = createRooms(1, 10);
  Collections.reverse(results);
  ReadResult<Room> readResult = ReadResult.forResult(results).build();
  Mockito.when(mockedDataSource.readData(Mockito.any(EdmEntitySet.class), Mockito.any(ReadOptions.class)))
      .thenReturn((ReadResult)readResult);

  ODataResponse result = dataSourceProcessor.readEntitySet(uriInfo, "application/json");

  StringHelper.Stream resultStream = StringHelper.toStream(result.getEntityAsStream());
  List<LinkedTreeMap<?, ?>> parsedResults = JsonHelper.getResults(resultStream.asString());
  Assert.assertEquals(10, parsedResults.size());
  Assert.assertEquals("Room with id: 1", parsedResults.get(0).get("Name"));
  Assert.assertEquals("Room with id: 9", parsedResults.get(9).get("Name"));
}
 
Example 27
Project: janos   File: DataSourceProcessorTest.java   View source code 6 votes vote down vote up
@Test
public void optimizedReadOrder() throws Exception {
  GetEntitySetUriInfo uriInfo = createMockedUriInfo("Rooms");
  Edm edm = EdmMock.createMockEdm();

  OrderByExpression exp = UriParserImpl.parseOrderBy(edm, edm.getEntityType("RefScenario", "Room"), "Name");
  Mockito.when(uriInfo.getOrderBy()).thenReturn(exp);

  List<Room> results = createRooms(1, 10);
  Collections.shuffle(results);
  ReadResult<Room> readResult = ReadResult.forResult(results).orderApplied().build();
  Mockito.when(mockedDataSource.readData(Mockito.any(EdmEntitySet.class), Mockito.any(ReadOptions.class)))
      .thenReturn((ReadResult)readResult);

  ODataResponse result = dataSourceProcessor.readEntitySet(uriInfo, "application/json");

  StringHelper.Stream resultStream = StringHelper.toStream(result.getEntityAsStream());
  List<LinkedTreeMap<?, ?>> parsedResults = JsonHelper.getResults(resultStream.asString());
  Assert.assertEquals(10, parsedResults.size());
  Assert.assertEquals("Room with id: 1", parsedResults.get(0).get("Name"));
  Assert.assertEquals("Room with id: 9", parsedResults.get(9).get("Name"));
}
 
Example 28
Project: janos   File: DataSourceProcessorTest.java   View source code 6 votes vote down vote up
@Test
public void readFilter() throws Exception {
  GetEntitySetUriInfo uriInfo = createMockedUriInfo("Rooms");
  Edm edm = EdmMock.createMockEdm();

  FilterExpression exp = UriParserImpl.parseFilter(edm, edm.getEntityType("RefScenario", "Room"), "Version gt 105");
  Mockito.when(uriInfo.getFilter()).thenReturn(exp);

  List<Room> results = createRooms(1, 10);
  ReadResult<Room> readResult = ReadResult.forResult(results).build();
  Mockito.when(mockedDataSource.readData(Mockito.any(EdmEntitySet.class), Mockito.any(ReadOptions.class)))
      .thenReturn((ReadResult)readResult);

  ODataResponse result = dataSourceProcessor.readEntitySet(uriInfo, "application/json");

  StringHelper.Stream resultStream = StringHelper.toStream(result.getEntityAsStream());
  List<LinkedTreeMap<?, ?>> parsedResults = JsonHelper.getResults(resultStream.asString());
  Assert.assertEquals(5, parsedResults.size());
  Assert.assertEquals("Room with id: 10", parsedResults.get(0).get("Name"));
  Assert.assertEquals("Room with id: 9", parsedResults.get(4).get("Name"));
}
 
Example 29
Project: janos   File: DataSourceProcessorTest.java   View source code 6 votes vote down vote up
@Test
public void readSkip() throws Exception {
  GetEntitySetUriInfo uriInfo = createMockedUriInfo("Rooms");

  Mockito.when(uriInfo.getSkip()).thenReturn(5);
  Mockito.when(uriInfo.getSkipToken()).thenReturn("2");

  List<Room> results = createRooms(1, 10);
  ReadResult<Room> readResult = ReadResult.forResult(results).build();
  Mockito.when(mockedDataSource.readData(Mockito.any(EdmEntitySet.class), Mockito.any(ReadOptions.class)))
      .thenReturn((ReadResult)readResult);

  ODataResponse result = dataSourceProcessor.readEntitySet(uriInfo, "application/json");

  StringHelper.Stream resultStream = StringHelper.toStream(result.getEntityAsStream());
  List<LinkedTreeMap<?, ?>> parsedResults = JsonHelper.getResults(resultStream.asString());
  Assert.assertEquals(3, parsedResults.size());
  Assert.assertEquals("Room with id: 7", parsedResults.get(0).get("Name"));
  Assert.assertEquals("Room with id: 9", parsedResults.get(2).get("Name"));
}
 
Example 30
Project: janos   File: DataSourceProcessorTest.java   View source code 6 votes vote down vote up
@Test
public void readOptimizedSkip() throws Exception {
  GetEntitySetUriInfo uriInfo = createMockedUriInfo("Rooms");

  Mockito.when(uriInfo.getSkip()).thenReturn(5);
  Mockito.when(uriInfo.getSkipToken()).thenReturn("2");

  List<Room> results = createRooms(1, 10);
  ReadResult<Room> readResult = ReadResult.forResult(results).skipApplied().build();
  Mockito.when(mockedDataSource.readData(Mockito.any(EdmEntitySet.class), Mockito.any(ReadOptions.class)))
      .thenReturn((ReadResult)readResult);

  ODataResponse result = dataSourceProcessor.readEntitySet(uriInfo, "application/json");

  StringHelper.Stream resultStream = StringHelper.toStream(result.getEntityAsStream());
  List<LinkedTreeMap<?, ?>> parsedResults = JsonHelper.getResults(resultStream.asString());
  Assert.assertEquals(10, parsedResults.size());
  Assert.assertEquals("Room with id: 1", parsedResults.get(0).get("Name"));
  Assert.assertEquals("Room with id: 9", parsedResults.get(9).get("Name"));
}
 
Example 31
Project: janos   File: EntitySetJsonTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings(value = "unchecked")
public void entitySetRooms() throws Exception {
  HttpResponse response =
      callUri("Rooms", HttpHeaders.ACCEPT, HttpContentType.APPLICATION_JSON, HttpStatusCodes.OK);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);

  String body = getBody(response);
  LinkedTreeMap<?, ?> map = getLinkedTreeMap(body);

  List<LinkedTreeMap<String, String>> results = (List) map.get("results");
  assertFalse(results.isEmpty());

  LinkedTreeMap<String, String> firstRoom = null;
  for (LinkedTreeMap<String, String> result: results) {
    if(result.get("Name").equals("Small green room")) {
      firstRoom = result;
    }
  }
  assertNotNull(firstRoom);
  assertEquals("Small green room", firstRoom.get("Name"));
  assertEquals(20.0, firstRoom.get("Seats"));
  assertEquals(42.0, firstRoom.get("Version"));
}
 
Example 32
Project: janos   File: EntitySetJsonTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings(value = "unchecked")
public void entitySetRoomsSkip() throws Exception {
  HttpResponse response =
      callUri("Rooms?$skip=1", HttpHeaders.ACCEPT, HttpContentType.APPLICATION_JSON, HttpStatusCodes.OK);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);

  String body = getBody(response);
  LinkedTreeMap<?, ?> map = getLinkedTreeMap(body);

  List<LinkedTreeMap<String, String>> results = (List) map.get("results");
  assertFalse(results.isEmpty());
  //
  assertTrue(roomsCount() != results.size());

  LinkedTreeMap<String, String> roomToCheck = null;
  for (LinkedTreeMap<String, String> result: results) {
    if(result.get("Name").equals("Small dark green room")) {
      roomToCheck = result;
    }
  }
  assertNotNull(roomToCheck);
  assertEquals("Small dark green room", roomToCheck.get("Name"));
  assertEquals(30.0, roomToCheck.get("Seats"));
  assertEquals(2.0, roomToCheck.get("Version"));
}
 
Example 33
Project: janos   File: EntityJsonTest.java   View source code 6 votes vote down vote up
@SuppressWarnings(value = "unchecked")
private String requestRoomId() throws Exception {
  HttpResponse response =
      callUri("Rooms", HttpHeaders.ACCEPT, HttpContentType.APPLICATION_JSON, HttpStatusCodes.OK);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);

  String body = getBody(response);
  LinkedTreeMap<?, ?> map = getLinkedTreeMap(body);

  List<LinkedTreeMap<String, String>> results = (List) map.get("results");

  for (LinkedTreeMap<String, String> result : results) {
    if(result.get("Name").equals("Small green room")) {
      return result.get("Id");
    }
  }
  return null;
}
 
Example 34
Project: ButterRemote-Android   File: PopcornTimeRpcClient.java   View source code 6 votes vote down vote up
/**
 * Get current viewstack of the application
 * @param callback Callback for the request
 * @return ResponseFuture
 */
public Call getViewstack(final Callback callback) {
    RpcRequest request  = new RpcRequest("getviewstack", RequestId.GET_VIEWSTACK);
    if(Version.compare(mVersion, ZERO_VERSION)) {
        return request(request, callback);
    } else {
        return request(request, new Callback() {
            @Override
            public void onCompleted(Exception e, RpcResponse result) {
                try {
                    if (e == null && result != null && result.result != null) {
                        if (result.result instanceof ArrayList) {
                            ArrayList list = (ArrayList) result.result;
                            LinkedTreeMap<String, Object> map = new LinkedTreeMap<String, Object>();
                            map.put("viewstack", list.get(0));
                            result.result = map;
                        }
                    }
                    callback.onCompleted(e, result);
                } catch(Exception exception) {
                    exception.printStackTrace();
                }
            }
        });
    }
}
 
Example 35
Project: ButterRemote-Android   File: PopcornTimeRpcClient.java   View source code 6 votes vote down vote up
/**
 * Get available subtitles for the current playing or selected video
 * @param callback Callback for the request
 * @return ResponseFuture
 */
public Call getSubtitles(final Callback callback) {
    RpcRequest request  = new RpcRequest("getsubtitles", RequestId.GET_SUBTITLES);
    if(Version.compare(mVersion, ZERO_VERSION)) {
        return request(request, callback);
    } else {
        return request(request, new Callback() {
            @Override
            public void onCompleted(Exception e, RpcResponse result) {
                if (e == null && result != null && result.result != null) {
                    ArrayList list = (ArrayList) result.result;
                    LinkedTreeMap<String, Object> map = new LinkedTreeMap<String, Object>();
                    map.put("subtitles", list.get(0));
                    result.result = map;
                }
                callback.onCompleted(e, result);
            }
        });
    }
}
 
Example 36
Project: olingo-odata2   File: FilterToJsonTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testToJsonBinaryProperty() throws Exception {
  FilterExpression expression = UriParser.parseFilter(null, null, "a eq b");
  String jsonString = toJson(expression);
  Gson gsonConverter = new Gson();

  LinkedTreeMap<String, Object> jsonMap = gsonConverter.fromJson(jsonString, LinkedTreeMap.class);
  checkBinary(jsonMap, "eq", null);

  LinkedTreeMap<String, Object> left = (LinkedTreeMap<String, Object>) jsonMap.get(LEFT);
  checkProperty(left, null, "a");

  LinkedTreeMap<String, Object> right = (LinkedTreeMap<String, Object>) jsonMap.get(RIGHT);
  checkProperty(right, null, "b");
}
 
Example 37
Project: olingo-odata2   File: FilterToJsonTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testToJsonBinaryLiteral() throws Exception {
  FilterExpression expression = UriParser.parseFilter(null, null, "'a' eq 'b'");
  String jsonString = toJson(expression);
  Gson gsonConverter = new Gson();

  LinkedTreeMap<String, Object> jsonMap = gsonConverter.fromJson(jsonString, LinkedTreeMap.class);
  checkBinary(jsonMap, "eq", "Edm.Boolean");

  LinkedTreeMap<String, Object> left = (LinkedTreeMap<String, Object>) jsonMap.get(LEFT);
  checkLiteral(left, "Edm.String", "a");

  LinkedTreeMap<String, Object> right = (LinkedTreeMap<String, Object>) jsonMap.get(RIGHT);
  checkLiteral(right, "Edm.String", "b");
}
 
Example 38
Project: olingo-odata2   File: FilterToJsonTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testToJsonMember() throws Exception {
  FilterExpression expression = UriParser.parseFilter(null, null, "Location/Country");
  String jsonString = toJson(expression);
  Gson gsonConverter = new Gson();

  LinkedTreeMap<String, Object> jsonMap = gsonConverter.fromJson(jsonString, LinkedTreeMap.class);
  checkMember(jsonMap, null);

  LinkedTreeMap<String, Object> source = (LinkedTreeMap<String, Object>) jsonMap.get(SOURCE);
  checkProperty(source, null, "Location");

  LinkedTreeMap<String, Object> path = (LinkedTreeMap<String, Object>) jsonMap.get(PATH);
  checkProperty(path, null, "Country");
}
 
Example 39
Project: olingo-odata2   File: FilterToJsonTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testToJsonMember2() throws Exception {
  FilterExpression expression = UriParser.parseFilter(null, null, "Location/Country/PostalCode");
  String jsonString = toJson(expression);
  Gson gsonConverter = new Gson();

  LinkedTreeMap<String, Object> jsonMap = gsonConverter.fromJson(jsonString, LinkedTreeMap.class);
  checkMember(jsonMap, null);

  LinkedTreeMap<String, Object> source1 = (LinkedTreeMap<String, Object>) jsonMap.get(SOURCE);
  checkMember(source1, null);

  LinkedTreeMap<String, Object> source2 = (LinkedTreeMap<String, Object>) source1.get(SOURCE);
  checkProperty(source2, null, "Location");

  LinkedTreeMap<String, Object> path1 = (LinkedTreeMap<String, Object>) source1.get(PATH);
  checkProperty(path1, null, "Country");

  LinkedTreeMap<String, Object> path = (LinkedTreeMap<String, Object>) jsonMap.get(PATH);
  checkProperty(path, null, "PostalCode");
}
 
Example 40
Project: olingo-odata2   File: EntryJsonCreateInlineTest.java   View source code 6 votes vote down vote up
@Test
public void createEntryRoomWithInlineEmptyFeedArray() throws Exception {
  String content = "{\"d\":{\"__metadata\":{\"id\":\"" + getEndpoint() + "Rooms('1')\","
      + "\"uri\":\"" + getEndpoint() + "Rooms('1')\",\"type\":\"RefScenario.Room\","
      + "\"etag\":\"W/\\\"3\\\"\"},"
      + "\"Id\":\"1\",\"Name\":\"Room 104\",\"Seats\":4,\"Version\":2,"
      + "\"nr_Employees\":[],"
      + "\"nr_Building\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('1')/nr_Building\"}}}}";
  HttpResponse response =
      postUri("Rooms", content, HttpContentType.APPLICATION_JSON, HttpHeaders.ACCEPT,
          HttpContentType.APPLICATION_JSON, HttpStatusCodes.CREATED);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);
  checkEtag(response, "W/\"2\"");

  String body = getBody(response);
  LinkedTreeMap<?, ?> map = getLinkedTreeMap(body);
  assertEquals("104", map.get("Id"));
  assertEquals("Room 104", map.get("Name"));

  @SuppressWarnings("unchecked")
  LinkedTreeMap<String, String> metadataMap = (LinkedTreeMap<String, String>) map.get("__metadata");
  assertNotNull(metadataMap);
  assertEquals(getEndpoint() + "Rooms('104')", metadataMap.get("id"));
  assertEquals("RefScenario.Room", metadataMap.get("type"));
  assertEquals(getEndpoint() + "Rooms('104')", metadataMap.get("uri"));
}