com.google.gson.internal.LinkedTreeMap Java Examples

The following examples show how to use com.google.gson.internal.LinkedTreeMap. 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: GenericJsonDeserializerTest.java    From bender with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNestedObjField() throws UnsupportedEncodingException, IOException, FieldNotFoundException {
  String input = TestUtils.getResourceString(this.getClass(), "basic.json");

  GenericJsonDeserializer deser = new GenericJsonDeserializer(Collections.emptyList());
  deser.init();
  DeserializedEvent event = deser.deserialize(input);

  Map<String, String> expected = new HashMap<String, String>();
  expected.put("foo", "bar");
  Object o = event.getField("$.an_obj");
  assertTrue(o instanceof JsonObject);

  JsonObject actual = (JsonObject) o;
  Gson gson = new Gson();

  assertEquals(expected, gson.fromJson(actual, LinkedTreeMap.class));
}
 
Example #2
Source File: FilterToJsonTest.java    From olingo-odata2 with Apache License 2.0 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 #3
Source File: IrrigationScheduleCommandEditorFragment.java    From arcusandroid with Apache License 2.0 6 votes vote down vote up
@Override
public void updateView() {
    if(isEditMode()) {
        ArrayList<LinkedTreeMap<String, Object>> events = getScheduleEvents();
        for(LinkedTreeMap<String, Object> item : events) {
            String eventId = (String)item.get("eventId");
            if(eventId.equals(getTimeOfDayCommandId())) {
                switch(title) {
                    case IrrigationSchedule.TYPE_WEEKLY:
                        parseEventDays(item);
                        break;
                    default:
                        break;
                }
            }
        }
    }
    rebind(true, getString(R.string.irrigation_start_time), getString(R.string.irrigation_start_time_description));

}
 
Example #4
Source File: IrrigationScheduleCommandEditorFragment.java    From arcusandroid with Apache License 2.0 6 votes vote down vote up
private ArrayList<LinkedTreeMap<String, Object>> getScheduleEvents() {
    if(title == null) {
        title = getArguments().getString(TITLE);
    }
    ArrayList<LinkedTreeMap<String, Object>> events = new ArrayList<>();
    switch(title) {
        case IrrigationScheduleStatus.MODE_WEEKLY:
            events = controller.getWeeklySchedule(getDeviceAddress());
            break;
        case IrrigationScheduleStatus.MODE_INTERVAL:
            events = controller.getIntervalSchedule(getDeviceAddress());
            break;
        case IrrigationScheduleStatus.MODE_ODD:
            events = controller.getOddSchedule(getDeviceAddress());
            break;
        case IrrigationScheduleStatus.MODE_EVEN:
            events = controller.getEvenSchedule(getDeviceAddress());
            break;
    }
    return events;
}
 
Example #5
Source File: EntryJsonCreateTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void createEntryEmployee() throws Exception {
  String content = "{iVBORw0KGgoAAAANSUhEUgAAAB4AAAAwCAIAAACJ9F2zAAAAA}";

  assertNotNull(content);
  HttpResponse response =
      postUri("Employees", content, HttpContentType.TEXT_PLAIN, HttpHeaders.ACCEPT, HttpContentType.APPLICATION_JSON,
          HttpStatusCodes.CREATED);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);

  String body = getBody(response);
  LinkedTreeMap<?, ?> map = getLinkedTreeMap(body);
  assertEquals("7", map.get("EmployeeId"));
  assertEquals("Employee 7", map.get("EmployeeName"));
  assertNull(map.get("EntryData"));
  response = callUri("Employees('7')/$value");
  checkMediaType(response, HttpContentType.TEXT_PLAIN);
}
 
Example #6
Source File: AccountService.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Objects that are not mapped to a known response can be processed here
 *
 * @param message Websocket Message
 */
private void handleNullMessageTypes(String message) {
    try {
        Object o = gson.fromJson(message, Object.class);
        if (o instanceof LinkedTreeMap) {
            processLinkedTreeMap((LinkedTreeMap) o);
        } else {
            requestQueue.poll();
            processQueue();
        }
    } catch (JsonSyntaxException e) {
        ExceptionHandler.handle(e);
        requestQueue.poll();
        processQueue();
    }
}
 
Example #7
Source File: EntryJsonCreateInlineTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void createEntryRoomWithInlineEmptyFeedObject() 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\":{\"results\":[]},"
      + "\"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"));
}
 
Example #8
Source File: JsonUtil.java    From telekom-workflow-engine with MIT License 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 #9
Source File: EntryJsonCreateTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void createEntryRoomWithLink() 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\","
      + "\"nr_Employees\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('1')/nr_Employees\"}},"
      + "\"nr_Building\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('1')/nr_Building\"}}}}";
  assertNotNull(content);
  HttpResponse response =
      postUri("Rooms", content, HttpContentType.APPLICATION_JSON, HttpHeaders.ACCEPT,
          HttpContentType.APPLICATION_JSON, HttpStatusCodes.CREATED);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);

  String body = getBody(response);
  LinkedTreeMap<?, ?> map = getLinkedTreeMap(body);
  assertEquals("104", map.get("Id"));
  assertEquals("Room 104", map.get("Name"));
  @SuppressWarnings("unchecked")
  LinkedTreeMap<String, Object> employeesMap = (LinkedTreeMap<String, Object>) map.get("nr_Employees");
  assertNotNull(employeesMap);
  @SuppressWarnings("unchecked")
  LinkedTreeMap<String, String> deferredMap = (LinkedTreeMap<String, String>) employeesMap.get("__deferred");
  assertNotNull(deferredMap);
  assertEquals(getEndpoint() + "Rooms('104')/nr_Employees", deferredMap.get("uri"));
}
 
Example #10
Source File: AccountService.java    From nano-wallet-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Process a linked tree map to see if there are pending blocks to handle
 *
 * @param linkedTreeMap Linked Tree Map
 */
private void processLinkedTreeMap(LinkedTreeMap linkedTreeMap) {
    if (linkedTreeMap.containsKey("blocks")) {
        // this is a set of blocks
        Object blocks = linkedTreeMap.get("blocks");
        if (blocks instanceof LinkedTreeMap) {
            // blocks is not empty
            Set keys = ((LinkedTreeMap) blocks).keySet();
            for (Object key : keys) {
                try {
                    PendingTransactionResponseItem pendingTransactionResponseItem = new Gson().fromJson(String.valueOf(((LinkedTreeMap) blocks).get(key)), PendingTransactionResponseItem.class);
                    pendingTransactionResponseItem.setHash(key.toString());
                    handleTransactionResponse(pendingTransactionResponseItem);
                } catch (Exception e) {
                    ExceptionHandler.handle(e);
                }
            }
        }
    }
    requestQueue.poll();
    processQueue();
}
 
Example #11
Source File: JsonSerializerTest.java    From mobile-messaging-sdk-android with Apache License 2.0 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 #12
Source File: StageTransform.java    From gocd-yaml-config-plugin with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> inverseTransform(Map<String, Object> stage) {
    if (stage == null) {
        return stage;
    }
    String stageName = (String) stage.get(JSON_STAGE_NAME_FIELD);
    Map<String, Object> inverseStage = new LinkedTreeMap<>();
    Map<String, Object> stageData = new LinkedTreeMap<>();

    addOptionalValue(stageData, stage, JSON_STAGE_FETCH_FIELD, YAML_STAGE_FETCH_FIELD);
    addOptionalValue(stageData, stage, JSON_STAGE_NEVER_CLEAN_FIELD, YAML_STAGE_KEEP_ARTIFACTS_FIELD);
    addOptionalValue(stageData, stage, JSON_STAGE_CLEAN_WORK_FIELD, YAML_STAGE_CLEAN_WORK_FIELD);
    addOptionalValue(stageData, stage, JSON_STAGE_APPROVAL_ALLOW_ONLY_ON_SUCCESS_FIELD, YAML_STAGE_APPROVAL_ALLOW_ONLY_ON_SUCCESS_FIELD);

    addInverseApproval(stageData, stage);

    Map<String, Object> yamlEnvVariables = environmentTransform.inverseTransform((List<Map<String, Object>>) stage.get(JSON_ENV_VAR_FIELD));
    if (yamlEnvVariables != null && yamlEnvVariables.size() > 0)
        stageData.putAll(yamlEnvVariables);

    addInverseJobs(stageData, (List<Map<String, Object>>) stage.get(JSON_STAGE_JOBS_FIELD));

    inverseStage.put(stageName, stageData);
    return inverseStage;
}
 
Example #13
Source File: ConfigurationTransform.java    From gocd-yaml-config-plugin with Apache License 2.0 6 votes vote down vote up
void addInverseConfiguration(Map<String, Object> taskData, Map<String, Object> task) {
    List<Map<String, Object>> jsonOptions = (List<Map<String, Object>>) task.get(JSON_PLUGIN_CONFIGURATION_FIELD);
    if (jsonOptions == null)
        return;

    Map<String, Object> options = new LinkedTreeMap<>();
    Map<String, Object> secureOptions = new LinkedTreeMap<>();

    for (Map<String, Object> option : jsonOptions) {
        if (option.containsKey(JSON_PLUGIN_CONFIG_ENCRYPTED_VALUE_FIELD)) {
            secureOptions.put((String) option.get(JSON_PLUGIN_CONFIG_KEY_FIELD), option.get(JSON_PLUGIN_CONFIG_ENCRYPTED_VALUE_FIELD));
        } else {
            options.put((String) option.get(JSON_PLUGIN_CONFIG_KEY_FIELD), option.get(JSON_PLUGIN_CONFIG_VALUE_FIELD));
        }
    }

    if (options.size() > 0)
        taskData.put(YAML_PLUGIN_STD_CONFIG_FIELD, options);
    if (secureOptions.size() > 0)
        taskData.put(YAML_PLUGIN_SEC_CONFIG_FIELD, secureOptions);
}
 
Example #14
Source File: OdooWrapper.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
private OUser parseUserObject(OUser user, OdooResult result) {
    // Odoo 10.0+ returns array of object in read method
    if (result.containsKey("result") && result.get("result") instanceof ArrayList) {
        List<LinkedTreeMap> items = (List<LinkedTreeMap>) result.get("result");
        result = new OdooResult();
        result.putAll(items.get(0));
    }
    user.setName(result.getString("name"));
    user.setAvatar(result.getString("image_medium"));
    user.setTimezone(result.getString("tz"));
    Double partner_id = (Double) result.getArray("partner_id").get(0);
    Double company_id = (Double) result.getArray("company_id").get(0);
    user.setPartnerId(partner_id.intValue());
    user.setCompanyId(company_id.intValue());
    if (mVersion.getVersionNumber() == 7) {
        //FIX: Odoo 7 Not returning company id with user login details
        odooSession.setCompanyId(company_id.intValue());
    }
    return user;
}
 
Example #15
Source File: JobTransform.java    From gocd-yaml-config-plugin with Apache License 2.0 6 votes vote down vote up
private void addInverseArtifacts(Map<String, Object> jobData, Map<String, Object> job) {
    List<Map<String, Object>> artifacts = (List<Map<String, Object>>) job.get(JSON_JOB_ARTIFACTS_FIELD);
    if (artifacts == null || artifacts.isEmpty())
        return;

    List<Map<String, Object>> inverseArtifacts = new ArrayList<>();
    for (Map<String, Object> artifact : artifacts) {
        Map<String, Object> inverseArtifact = new LinkedTreeMap<>();

        String type = (String) artifact.remove("type");
        inverseArtifact.put(type, artifact);
        inverseArtifacts.add(inverseArtifact);
        handleExternalArtifactConfiguration(type, inverseArtifact);
    }

    jobData.put(YAML_JOB_ARTIFACTS_FIELD, inverseArtifacts);
}
 
Example #16
Source File: TaskTransform.java    From gocd-yaml-config-plugin with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> inverseTransform(Map<String, Object> task) {
    String type = (String) task.get(JSON_TASK_TYPE_FIELD);
    Map<String, Object> inverseTask = new LinkedTreeMap<>();
    Map<String, Object> taskData = new LinkedTreeMap<>();

    addInverseOnCancel(taskData, task);

    addOptionalValue(taskData, task, JSON_TASK_PLUGIN_CONFIGURATION_FIELD, YAML_PLUGIN_CONFIGURATION_FIELD);
    addInverseConfiguration(taskData, task);

    addOptionalValue(taskData, task, JSON_TASK_IS_FILE_FIELD, YAML_TASK_IS_FILE_FIELD);
    addOptionalList(taskData, task, JSON_TASK_EXEC_ARGS_FIELD, YAML_TASK_EXEC_ARGS_FIELD);

    for (Map.Entry<String, Object> taskProp : task.entrySet()) {
        if (yamlSpecialKeywords.contains(taskProp.getKey()))
            continue;
        if (taskProp.getValue() instanceof String)
            taskData.put(taskProp.getKey(), taskProp.getValue());
    }

    inverseTask.put(type, taskData);
    return inverseTask;
}
 
Example #17
Source File: FilterToJsonTest.java    From olingo-odata2 with Apache License 2.0 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 #18
Source File: FilterToJsonTest.java    From olingo-odata2 with Apache License 2.0 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 #19
Source File: NodeBodyUpdate.java    From alfresco-client-sdk with Apache License 2.0 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 #20
Source File: StageTransform.java    From gocd-yaml-config-plugin with Apache License 2.0 5 votes vote down vote up
private void addInverseApproval(Map<String, Object> stageData, Map<String, Object> stage) {
    Map<String, Object> approval = (Map<String, Object>) stage.get(JSON_STAGE_APPROVAL_FIELD);
    Map<String, Object> inverseApproval = new LinkedTreeMap<>();
    if (approval == null)
        return;

    addRequiredValue(inverseApproval, approval, JSON_STAGE_APPROVAL_TYPE_FIELD, YAML_STAGE_APPROVAL_TYPE_FIELD);
    addOptionalValue(inverseApproval, approval, JSON_STAGE_APPROVAL_ALLOW_ONLY_ON_SUCCESS_FIELD, YAML_STAGE_APPROVAL_ALLOW_ONLY_ON_SUCCESS_FIELD);
    addOptionalList(inverseApproval, approval, JSON_STAGE_APPROVAL_ROLES_FIELD, YAML_STAGE_APPROVAL_ROLES_FIELD);
    addOptionalList(inverseApproval, approval, JSON_STAGE_APPROVAL_USERS_FIELD, YAML_STAGE_APPROVAL_USERS_FIELD);

    stageData.put(YAML_STAGE_APPROVAL_FIELD, inverseApproval);
}
 
Example #21
Source File: LawnAndGardenScheduleController.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
public ArrayList<LinkedTreeMap<String, Object>> filterDeletedEvents(ArrayList<LinkedTreeMap<String, Object>> events) {
    ArrayList<LinkedTreeMap<String, Object>> returnList = new ArrayList<>();

    for(LinkedTreeMap<String, Object> event : events) {
        if(event.get("status") != null) {
            String status = (String)event.get("status");
            if(!status.equals("DELETING") && !status.equals("DELETED")) {
                returnList.add(event);
            }
        }
    }
    return returnList;
}
 
Example #22
Source File: GenericOutputFormatterTest.java    From MultiChainJavaAPI with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
  public void testFormatBlock() {
    String blockJsonValue =
        "{\"hash\": \"00cd11ab4a7146236595c29f52a874521845cb2a417da4e938266e1a3a1f3bb2\","
            + "\"miner\": \"13SKg7Qw7UxPWvjDMkskyvKU7HfM9mz1KHi43E\"," + "\"confirmations\": 235,"
            + "\"size\": 241," + "\"height\": 0," + "\"version\": 1,"
            + "\"merkleroot\": \"428c3d6b97720175dba80c893ec97407522f564af5665ecff0684cd8d74eae6e\","
            + "\"tx\": [" + "  \"428c3d6b97720175dba80c893ec97407522f564af5665ecff0684cd8d74eae6e\""
            + "]," + "\"time\": 1543504235," + "\"nonce\": 97," + "\"bits\": \"2000ffff\","
            + "\"difficulty\": 5.96046447753906E-8,"
            + "\"chainwork\": \"0000000000000000000000000000000000000000000000000000000000000100\","
            + "\"nextblockhash\": \"0074f303c0b50dcf4a0f8e48840c14af9dd5666f5f953b154b9d7d2549ea02f9\""
            + "}";

    Class<?>[] returnedTypes = CommandElt.GETBLOCK.getReturnedClass();
    LinkedTreeMap<String, Object> linkedTreeMapValue =
        new Gson().fromJson(blockJsonValue, LinkedTreeMap.class);

    Object returnedValue = GenericOutputFormatter.format(linkedTreeMapValue, returnedTypes);

    System.out.println(returnedValue);
    System.out.println(returnedValue.getClass());

    Assert.assertNotNull(returnedValue);

  }
 
Example #23
Source File: JsonEntryEntitySerializerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void serializeWithCustomSrcAndTypeAttributeOnRoom() throws Exception {
  Entity roomData = new Entity();
  roomData.addProperty("Id", "1");
  roomData.addProperty("Name", "Neu Schwanstein");
  roomData.addProperty("Seats", new Integer(20));
  roomData.addProperty("Version", new Integer(3));

  String mediaResourceSourceKey = "~src";
  roomData.addProperty(mediaResourceSourceKey, "http://localhost:8080/images/image1");
  String mediaResourceMimeTypeKey = "~type";
  roomData.addProperty(mediaResourceMimeTypeKey, "image/jpeg");
  roomData.setWriteProperties(EntitySerializerProperties.serviceRoot(URI.create(BASE_URI)).
      includeMetadata(true).build());

  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  EdmEntityType roomType = roomsSet.getEntityType();
  EdmMapping mapping = mock(EdmMapping.class);
  when(roomType.getMapping()).thenReturn(mapping);
  when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey);
  when(mapping.getMediaResourceMimeTypeKey()).thenReturn(mediaResourceMimeTypeKey);

  ODataResponse response = new JsonSerializerDeserializer().writeEntry(roomsSet, roomData);
  String jsonString = verifyResponse(response);
  Gson gson = new Gson();
  LinkedTreeMap<String, Object> jsonMap = gson.fromJson(jsonString, LinkedTreeMap.class);
  jsonMap = (LinkedTreeMap<String, Object>) jsonMap.get("__metadata");

  assertNull(jsonMap.get("media_src"));
  assertNull(jsonMap.get("content_type"));
  assertNull(jsonMap.get("edit_media"));
}
 
Example #24
Source File: EntryJsonCreateTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createAndModifyEntryEmployee() throws Exception {
  String content = "{iVBORw0KGgoAAAANSUhEUgAAAB4AAAAwCAIAAACJ9F2zAAAAA}";

  assertNotNull(content);
  HttpResponse createResponse =
      postUri("Employees", content, HttpContentType.TEXT_PLAIN, HttpHeaders.ACCEPT, HttpContentType.APPLICATION_JSON,
          HttpStatusCodes.CREATED);
  checkMediaType(createResponse, HttpContentType.APPLICATION_JSON);

  String body = getBody(createResponse);
  LinkedTreeMap<?,?> map = getStringMap(body);
  String id = (String) map.get("EmployeeId");
  assertNull(map.get("EmployeeName"));

  putUri("Employees('" + id + "')", JSON_EMPLOYEE, HttpContentType.APPLICATION_JSON, HttpStatusCodes.NO_CONTENT);

  HttpResponse updateResponse = callUri("Employees('" + id + "')", "Accept", HttpContentType.APPLICATION_JSON);
  checkMediaType(updateResponse, HttpContentType.APPLICATION_JSON);
  String updatedBody = getBody(updateResponse);
  LinkedTreeMap<?,?> updatedMap = getStringMap(updatedBody);
  assertNotNull(updatedMap.get("EmployeeId"));
  assertEquals("Douglas", updatedMap.get("EmployeeName"));
  assertNull(updatedMap.get("EntryData"));

  LinkedTreeMap<?,?> location = (LinkedTreeMap<?,?>) updatedMap.get("Location");
  assertEquals("Britian", location.get("Country"));

  LinkedTreeMap<?,?> city = (LinkedTreeMap<?,?>) location.get("City");
  assertEquals("12345", city.get("PostalCode"));
  assertEquals("Sample", city.get("CityName"));
}
 
Example #25
Source File: GenericOutputFormatter.java    From MultiChainJavaAPI with GNU General Public License v3.0 5 votes vote down vote up
public static final <T> T format(Object jsonValue, Class<T> valueType) {
  T returnedValue = null;

  if (jsonValue != null
      && (LinkedTreeMap.class.isInstance(jsonValue) || valueType.isInstance(jsonValue))) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    String nomalizedJsonValue = gson.toJson(jsonValue);
    returnedValue = gson.fromJson(nomalizedJsonValue, valueType);
  }

  return returnedValue;
}
 
Example #26
Source File: ParcelOperation.java    From BadIntent with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NonNull
public static ArrayValue parseArrayValue(LinkedTreeMap receivedStructure) {
    return new ArrayValue(
            (ArrayList) receivedStructure.get("array"),
            ((Double) receivedStructure.get("len")).intValue(),
            ((Double) receivedStructure.get("offset")).intValue()
    );
}
 
Example #27
Source File: LawnAndGardenScheduleController.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
public ArrayList<LinkedTreeMap<String, Object>> getIntervalSchedule(String deviceAddress) {
    Map<String, Map<String, Object>> map = getLawnNGardenSubsystem().getIntervalSchedules();
    Map<String, Object> deviceMap = map.get(deviceAddress);

    if(deviceMap == null) {
        return new ArrayList<>();
    }

    ArrayList<LinkedTreeMap<String, Object>> events = (ArrayList<LinkedTreeMap<String, Object>>) deviceMap.get("events");
    return filterDeletedEvents(events);
}
 
Example #28
Source File: LightsNSwitchesEditController.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
private ClientFuture<ClientEvent> add(LightsNSwitchesScheduleDay modifyingDay) {
    ClientRequest request = new ClientRequest();

    request.setAddress(schedulerModel.getAddress());
    request.setCommand(WeeklySchedule.ScheduleWeeklyCommandRequest.NAME + ":" + LightsNSwitchesScheduleViewController.LNS_GROUP_ID);
    request.setAttribute(WeeklySchedule.ScheduleWeeklyCommandRequest.ATTR_DAYS, serializeDays(modifyingDay));
    request.setAttribute(WeeklySchedule.UpdateWeeklyCommandRequest.ATTR_MODE, modifyingDay.getTimeOfDay().getSunriseSunset().name());

    if (SunriseSunset.ABSOLUTE.equals(modifyingDay.getTimeOfDay().getSunriseSunset())) {
        request.setAttribute(WeeklySchedule.UpdateWeeklyCommandRequest.ATTR_TIME, modifyingDay.getTimeOfDay().toString());
    }
    else {
        request.setAttribute(WeeklySchedule.UpdateWeeklyCommandRequest.ATTR_OFFSETMINUTES, modifyingDay.getTimeOfDay().getOffset());
    }

    request.setAttribute(WeeklySchedule.ScheduleWeeklyCommandRequest.ATTR_ATTRIBUTES, serializeAttributes(modifyingDay));


    LinkedTreeMap map = (LinkedTreeMap)schedulerModel.get(Scheduler.ATTR_COMMANDS);
    if (map != null && map.size() == 0){
        setScheduleEnabled(schedulerModel.getTarget(), true);
    }

    return CorneaClientFactory.getClient()
          .request(request)
          .onFailure(onError);
}
 
Example #29
Source File: EntryJsonCreateInlineTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createThreeLevelsDeepInsert() throws Exception {
  String content =
      "{\"Name\" : \"Room 2\",\"nr_Building\" : {\"Name\" : \"Building 2\",\"nb_Rooms\" : {\"results\" : [{"
          + "\"nr_Employees\" : {\"__deferred\" : {\"uri\" : \"" + getEndpoint() + "Rooms('1')/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);

  String body = getBody(response);

  // Check inline building
  LinkedTreeMap<?, ?> map = getLinkedTreeMap(body);
  map = (LinkedTreeMap<?, ?>) map.get("nr_Building");
  assertNotNull(map);
  assertEquals("Building 2", map.get("Name"));

  // Check inline rooms of the inline building
  map = (LinkedTreeMap<?, ?>) map.get("nb_Rooms");
  assertNotNull(map);

  ArrayList<?> results = (ArrayList<?>) map.get("results");
  assertNotNull(results);
  assertEquals(2, results.size());
}
 
Example #30
Source File: LawnAndGardenScheduleController.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
public ArrayList<LinkedTreeMap<String, Object>> getOddSchedule(String deviceAddress) {
    Map<String, Map<String, Object>> map = getLawnNGardenSubsystem().getOddSchedules();
    Map<String, Object> deviceMap = map.get(deviceAddress);

    if(deviceMap == null) {
        return new ArrayList<>();
    }

    ArrayList<LinkedTreeMap<String, Object>> events = (ArrayList<LinkedTreeMap<String, Object>>) deviceMap.get("events");
    return filterDeletedEvents(events);
}