com.arm.mbed.cloud.sdk.common.GenericAdapter Maven / Gradle / Ivy
package com.arm.mbed.cloud.sdk.common;
import java.util.LinkedList;
import java.util.List;
import com.arm.mbed.cloud.sdk.annotations.Internal;
import com.arm.mbed.cloud.sdk.annotations.Preamble;
import com.arm.mbed.cloud.sdk.common.listing.ListResponse;
@Preamble(description = "Generic adapter")
@Internal
public class GenericAdapter {
private GenericAdapter() {
super();
}
/**
* Mapper interface.
*
* Utility in charge of converting an object U into an object T.
*
* @param
* Type of the object to convert from.
* @param
* Type of the object to convert to.
*/
public interface Mapper {
T map(U toBeMapped);
}
/**
* Paginated response from the server.
*
* A typical page returned from server when listing objects.
*
* @param
* type of objects listed
*/
public interface RespList {
Boolean getHasMore();
Integer getTotalCount();
String getAfter();
Integer getLimit();
String getOrder();
List getData();
}
/**
* Maps a page of objects U into a list of object T.
*
* @param respList
* page (i.e. paginated response from server)
* @param mapper
* mapper of each object.
* @param
* type of the object to be mapped from
* @param
* type of the object to be mapped to
* @return mapped list or null if list is null @see ListResponse
*/
public static ListResponse mapList(RespList respList, Mapper mapper) {
if (respList == null || mapper == null) {
return null;
}
final ListResponse responseList = new ListResponse<>(TranslationUtils.toBool(respList.getHasMore(), false),
TranslationUtils.toInt(respList.getTotalCount()), respList.getAfter(),
TranslationUtils.toInt(respList.getLimit()), Order.getOrder(respList.getOrder()));
if (respList.getData() == null || respList.getData().isEmpty()) {
return responseList;
}
for (final U resp : respList.getData()) {
responseList.addData(mapper.map(resp));
}
return responseList;
}
/**
* Maps a list of objects U into a list of object T.
*
* @param list
* to map.
* @param mapper
* mapper of each object.
* @param
* type of the object to be mapped from
* @param
* type of the object to be mapped to
* @return mapped list or null if list is null
*/
public static List mapList(List list, Mapper mapper) {
if (list == null || mapper == null) {
return null;
}
return mapList(list, new LinkedList(), mapper);
}
/**
* Maps a list of objects U into a list of object T.
*
* @param list
* to map.
* @param mappedList
* container of mapped objects
* @param mapper
* mapper of each object.
* @param
* type of the object to be mapped from
* @param
* type of the object to be mapped to
* @return mapped list
*/
public static List mapList(List list, List mappedList, Mapper mapper) {
if (list == null || mapper == null) {
return mappedList;
}
for (final U element : list) {
mappedList.add(mapper.map(element));
}
return mappedList;
}
}