use of org.eclipse.kapua.commons.model.query.FieldSortCriteria in project kapua by eclipse.
the class ServiceDAO method query.
/**
* Query entity utility method
*
* @param em
* @param interfaceClass
* result query interface class
* @param implementingClass
* result query implementation class
* @param resultContainer
* @param kapuaQuery
* @return
* @throws KapuaException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <I extends KapuaEntity, E extends I, L extends KapuaListResult<I>> L query(EntityManager em, Class<I> interfaceClass, Class<E> implementingClass, L resultContainer, KapuaQuery<I> kapuaQuery) throws KapuaException {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<E> criteriaSelectQuery = cb.createQuery(implementingClass);
//
// FROM
Root<E> entityRoot = criteriaSelectQuery.from(implementingClass);
EntityType<E> entityType = entityRoot.getModel();
//
// SELECT
criteriaSelectQuery.select(entityRoot);
//
// WHERE
ParameterExpression<Long> scopeIdParam = cb.parameter(Long.class);
Expression<Boolean> scopeIdExpr = cb.equal(entityRoot.get("scopeId"), scopeIdParam);
Map<ParameterExpression, Object> binds = new HashMap<ParameterExpression, Object>();
binds.put(scopeIdParam, kapuaQuery.getScopeId());
Expression<Boolean> expr = handleKapuaQueryPredicates(kapuaQuery.getPredicate(), binds, cb, entityRoot, entityRoot.getModel());
if (expr == null) {
criteriaSelectQuery.where(scopeIdExpr);
} else {
criteriaSelectQuery.where(cb.and(scopeIdExpr, expr));
}
// ORDER BY
if (kapuaQuery.getSortCriteria() != null) {
FieldSortCriteria sortCriteria = (FieldSortCriteria) kapuaQuery.getSortCriteria();
Order order;
if (SortOrder.ASCENDING.equals(sortCriteria.getSortOrder())) {
order = cb.asc(entityRoot.get(entityType.getSingularAttribute(sortCriteria.getAttributeName())));
} else {
order = cb.desc(entityRoot.get(entityType.getSingularAttribute(sortCriteria.getAttributeName())));
}
criteriaSelectQuery.orderBy(order);
}
//
// QUERY!
TypedQuery<E> query = em.createQuery(criteriaSelectQuery);
// Populate query parameters
for (ParameterExpression pe : binds.keySet()) {
query.setParameter(pe, binds.get(pe));
}
// Set offset
if (kapuaQuery.getOffset() != null) {
query.setFirstResult(kapuaQuery.getOffset().intValue());
}
// Set limit
if (kapuaQuery.getLimit() != null) {
query.setMaxResults(kapuaQuery.getLimit().intValue() + 1);
}
// Finally quering!
List<E> result = query.getResultList();
// Check limit exceeded
if (kapuaQuery.getLimit() != null && result.size() > kapuaQuery.getLimit().intValue()) {
result.remove(kapuaQuery.getLimit().intValue());
resultContainer.setLimitExceeded(true);
}
// Set results
resultContainer.addItems(result);
return resultContainer;
}
use of org.eclipse.kapua.commons.model.query.FieldSortCriteria in project kapua by eclipse.
the class GwtDeviceServiceImpl method findDeviceEvents.
public PagingLoadResult<GwtDeviceEvent> findDeviceEvents(PagingLoadConfig loadConfig, GwtDevice gwtDevice, Date startDate, Date endDate) throws GwtKapuaException {
ArrayList<GwtDeviceEvent> gwtDeviceEvents = new ArrayList<GwtDeviceEvent>();
BasePagingLoadResult<GwtDeviceEvent> gwtResults = null;
KapuaLocator locator = KapuaLocator.getInstance();
DeviceEventService des = locator.getService(DeviceEventService.class);
DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class);
try {
// prepare the query
BasePagingLoadConfig bplc = (BasePagingLoadConfig) loadConfig;
DeviceEventQuery query = deviceEventFactory.newQuery(KapuaEid.parseShortId(gwtDevice.getScopeId()));
KapuaAndPredicate andPredicate = new AndPredicate();
andPredicate.and(new AttributePredicate<KapuaId>(DeviceEventPredicates.DEVICE_ID, KapuaEid.parseShortId(gwtDevice.getId())));
// .and(new AttributePredicate<Date>(DeviceEventPredicates.RECEIVED_ON, startDate, Operator.GREATER_THAN));
// .and(new AttributePredicate<Date>(DeviceEventPredicates.RECEIVED_ON, startDate, Operator.LESS_THAN));
query.setPredicate(andPredicate);
query.setSortCriteria(new FieldSortCriteria(DeviceEventPredicates.RECEIVED_ON, SortOrder.DESCENDING));
query.setOffset(bplc.getOffset());
query.setLimit(bplc.getLimit());
// query execute
KapuaListResult<DeviceEvent> deviceEvents = des.query(query);
// prepare results
for (DeviceEvent deviceEvent : deviceEvents.getItems()) {
gwtDeviceEvents.add(KapuaGwtConverter.convert(deviceEvent));
}
gwtResults = new BasePagingLoadResult<GwtDeviceEvent>(gwtDeviceEvents);
gwtResults.setOffset(loadConfig.getOffset());
gwtResults.setTotalLength((int) des.count(query));
} catch (Throwable t) {
KapuaExceptionHandler.handle(t);
}
return gwtResults;
}
use of org.eclipse.kapua.commons.model.query.FieldSortCriteria in project kapua by eclipse.
the class DeviceExporterServlet method internalDoGet.
private void internalDoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// parameter extraction
String format = request.getParameter("format");
String scopeIdString = request.getParameter("scopeIdString");
// data exporter
DeviceExporter deviceExporter = null;
if ("xls".equals(format)) {
deviceExporter = new DeviceExporterExcel(response);
} else if ("csv".equals(format)) {
deviceExporter = new DeviceExporterCsv(response);
} else {
throw new IllegalArgumentException("format");
}
if (scopeIdString == null || scopeIdString.isEmpty()) {
throw new IllegalArgumentException("account");
}
deviceExporter.init(scopeIdString);
//
// get the devices and append them to the exporter
KapuaLocator locator = KapuaLocator.getInstance();
DeviceRegistryService drs = locator.getService(DeviceRegistryService.class);
DeviceFactory drf = locator.getFactory(DeviceFactory.class);
int resultsCount = 0;
int offset = 0;
// paginate through the matching message
DeviceQuery dq = drf.newQuery(KapuaEid.parseShortId(scopeIdString));
dq.setLimit(250);
// Inserting filter parameter if specified
AndPredicate andPred = new AndPredicate();
String clientId = request.getParameter("clientId");
if (clientId != null && !clientId.isEmpty()) {
andPred = andPred.and(new AttributePredicate<String>(DevicePredicates.CLIENT_ID, clientId, Operator.STARTS_WITH));
}
String displayName = request.getParameter("displayName");
if (displayName != null && !displayName.isEmpty()) {
andPred = andPred.and(new AttributePredicate<String>(DevicePredicates.DISPLAY_NAME, displayName, Operator.STARTS_WITH));
}
String serialNumber = request.getParameter("serialNumber");
if (serialNumber != null && !serialNumber.isEmpty()) {
andPred = andPred.and(new AttributePredicate<String>(DevicePredicates.SERIAL_NUMBER, serialNumber));
}
String deviceStatus = request.getParameter("deviceStatus");
if (deviceStatus != null && !deviceStatus.isEmpty()) {
andPred = andPred.and(new AttributePredicate<DeviceStatus>(DevicePredicates.STATUS, DeviceStatus.valueOf(deviceStatus)));
}
String sortAttribute = request.getParameter("sortAttribute");
if (sortAttribute != null && !sortAttribute.isEmpty()) {
String sortOrderString = request.getParameter("sortOrder");
SortOrder sortOrder;
if (sortOrderString != null && !sortOrderString.isEmpty()) {
sortOrder = SortOrder.valueOf(sortOrderString);
} else {
sortOrder = SortOrder.ASCENDING;
}
if (sortAttribute.compareTo("CLIENT_ID") == 0) {
dq.setSortCriteria(new FieldSortCriteria(DevicePredicates.CLIENT_ID, sortOrder));
} else if (sortAttribute.compareTo("DISPLAY_NAME") == 0) {
dq.setSortCriteria(new FieldSortCriteria(DevicePredicates.DISPLAY_NAME, sortOrder));
} else if (sortAttribute.compareTo("LAST_EVENT_ON") == 0) {
dq.setSortCriteria(new FieldSortCriteria(DevicePredicates.LAST_EVENT_ON, sortOrder));
}
}
dq.setPredicate(andPred);
KapuaListResult<Device> results = null;
do {
dq.setOffset(offset);
results = drs.query(dq);
deviceExporter.append(results);
offset += results.getSize();
resultsCount += results.getSize();
} while (results.getSize() > 0);
// Close things up
deviceExporter.close();
} catch (IllegalArgumentException iae) {
response.sendError(400, "Illegal value for query parameter: " + iae.getMessage());
return;
} catch (KapuaEntityNotFoundException eenfe) {
response.sendError(400, eenfe.getMessage());
return;
} catch (KapuaUnauthenticatedException eiae) {
response.sendError(401, eiae.getMessage());
return;
} catch (KapuaIllegalAccessException eiae) {
response.sendError(403, eiae.getMessage());
return;
} catch (Exception e) {
s_logger.error("Error creating device export", e);
throw new ServletException(e);
}
}
use of org.eclipse.kapua.commons.model.query.FieldSortCriteria in project kapua by eclipse.
the class Devices method getEvents.
/**
* Returns the events for the device identified by the specified
* ClientID under the account of the currently connected user.
* <p>
* If the flag DeviceEventsResult.limitExceeded is set, the maximum number
* of entries to be returned has been reached, more events exist and can
* be read by moving the offset forward in a new request
*
* @param deviceId
* The client ID of the device requested.
* @param limit
* Maximum number of entries to be returned.
* @param offset
* Starting offset for the entries to be returned.
* @param startDate
* Start date of the date range requested. The parameter
* is expressed as a long counting the number of milliseconds since
* January 1, 1970, 00:00:00 GMT. The default value of 0 means no
* start date. Alternatively, the date can be expressed as a string
* following the ISO 8601 format.
* @param endDate
* End date of the date range requested. The parameter
* is expressed as a long counting the number of milliseconds since
* January 1, 1970, 00:00:00 GMT. The default value of 0 means no
* start date. Alternatively, the date can be expressed as a string
* following the ISO 8601 format.
* @return The list of Events
*/
@GET
@Path("{deviceId}/events")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public DeviceEventListResult getEvents(@PathParam("deviceId") String deviceId, @QueryParam("limit") @DefaultValue("50") int limit, @QueryParam("offset") int offset, @QueryParam("startDate") String startDate, @QueryParam("endDate") String endDate) {
DeviceEventListResult deviceEvents = eventFactory.newDeviceListResult();
try {
KapuaId scopeId = KapuaSecurityUtils.getSession().getScopeId();
KapuaId id = KapuaEid.parseShortId(deviceId);
DeviceEventQuery query = eventFactory.newQuery(scopeId);
KapuaAndPredicate andPredicate = new AndPredicate();
andPredicate.and(new AttributePredicate<>(DeviceEventPredicates.DEVICE_ID, id));
// TODO Date filter not working?
if (startDate != null) {
DateTime parsedStartDate = DateTime.parse(startDate);
andPredicate = andPredicate.and(new AttributePredicate<>(DeviceEventPredicates.RECEIVED_ON, parsedStartDate.toDate(), KapuaAttributePredicate.Operator.GREATER_THAN));
}
if (endDate != null) {
DateTime parsedEndDate = DateTime.parse(endDate);
andPredicate = andPredicate.and(new AttributePredicate<>(DeviceEventPredicates.RECEIVED_ON, parsedEndDate.toDate(), KapuaAttributePredicate.Operator.LESS_THAN));
}
query.setPredicate(andPredicate);
query.setSortCriteria(new FieldSortCriteria(DeviceEventPredicates.RECEIVED_ON, FieldSortCriteria.SortOrder.DESCENDING));
query.setOffset(offset);
query.setLimit(limit);
// query execute
deviceEvents = (DeviceEventListResult) eventService.query(query);
} catch (Throwable t) {
handleException(t);
}
return returnNotNullEntity(deviceEvents);
}
use of org.eclipse.kapua.commons.model.query.FieldSortCriteria in project kapua by eclipse.
the class GwtDeviceServiceImpl method findDevices.
public PagingLoadResult<GwtDevice> findDevices(PagingLoadConfig loadConfig, String scopeIdString, GwtDeviceQueryPredicates predicates) throws GwtKapuaException {
KapuaLocator locator = KapuaLocator.getInstance();
DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class);
DeviceFactory deviceFactory = locator.getFactory(DeviceFactory.class);
List<GwtDevice> gwtDevices = new ArrayList<GwtDevice>();
BasePagingLoadResult<GwtDevice> gwtResults;
int totalResult = 0;
try {
BasePagingLoadConfig bplc = (BasePagingLoadConfig) loadConfig;
DeviceQuery deviceQuery = deviceFactory.newQuery(KapuaEid.parseShortId(scopeIdString));
deviceQuery.setLimit(bplc.getLimit() + 1);
deviceQuery.setOffset(bplc.getOffset());
AndPredicate andPred = new AndPredicate();
if (predicates.getClientId() != null) {
andPred = andPred.and(new AttributePredicate<String>(DevicePredicates.CLIENT_ID, predicates.getUnescapedClientId(), Operator.STARTS_WITH));
}
if (predicates.getDisplayName() != null) {
andPred = andPred.and(new AttributePredicate<String>(DevicePredicates.DISPLAY_NAME, predicates.getUnescapedDisplayName(), Operator.STARTS_WITH));
}
if (predicates.getSerialNumber() != null) {
andPred = andPred.and(new AttributePredicate<String>(DevicePredicates.SERIAL_NUMBER, predicates.getUnescapedSerialNumber()));
}
if (predicates.getDeviceStatus() != null) {
andPred = andPred.and(new AttributePredicate<DeviceStatus>(DevicePredicates.STATUS, DeviceStatus.valueOf(predicates.getDeviceStatus())));
}
if (predicates.getSortAttribute() != null) {
SortOrder sortOrder = SortOrder.ASCENDING;
if (predicates.getSortOrder().equals(SortOrder.DESCENDING.name())) {
sortOrder = SortOrder.DESCENDING;
}
if (predicates.getSortAttribute().equals(GwtDeviceQueryPredicates.GwtSortAttribute.CLIENT_ID.name())) {
deviceQuery.setSortCriteria(new FieldSortCriteria(DevicePredicates.CLIENT_ID, sortOrder));
} else if (predicates.getSortAttribute().equals(GwtDeviceQueryPredicates.GwtSortAttribute.DISPLAY_NAME.name())) {
deviceQuery.setSortCriteria(new FieldSortCriteria(DevicePredicates.DISPLAY_NAME, sortOrder));
} else if (predicates.getSortAttribute().equals(GwtDeviceQueryPredicates.GwtSortAttribute.LAST_EVENT_ON.name())) {
deviceQuery.setSortCriteria(new FieldSortCriteria(DevicePredicates.LAST_EVENT_ON, sortOrder));
}
} else {
deviceQuery.setSortCriteria(new FieldSortCriteria(DevicePredicates.CLIENT_ID, SortOrder.ASCENDING));
}
deviceQuery.setPredicate(andPred);
KapuaListResult<Device> devices = deviceRegistryService.query(deviceQuery);
totalResult = (int) deviceRegistryService.count(deviceQuery);
DeviceConnectionService deviceConnectionService = locator.getService(DeviceConnectionService.class);
DeviceEventService deviceEventService = locator.getService(DeviceEventService.class);
DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class);
DeviceEventQuery eventQuery = deviceEventFactory.newQuery(deviceQuery.getScopeId());
eventQuery.setLimit(1);
eventQuery.setSortCriteria(new FieldSortCriteria(DeviceEventPredicates.RECEIVED_ON, SortOrder.DESCENDING));
for (Device d : devices.getItems()) {
DeviceConnection deviceConnection = deviceConnectionService.findByClientId(d.getScopeId(), d.getClientId());
// Connection info
GwtDevice gwtDevice = KapuaGwtConverter.convert(d);
gwtDevice.setConnectionIp(deviceConnection.getClientIp());
gwtDevice.setGwtDeviceConnectionStatus(deviceConnection.getStatus().name());
gwtDevice.setLastEventOn(deviceConnection.getModifiedOn());
// Event infos
eventQuery.setPredicate(new AttributePredicate<KapuaId>(DeviceEventPredicates.DEVICE_ID, d.getId()));
KapuaListResult<DeviceEvent> events = deviceEventService.query(eventQuery);
if (!events.isEmpty()) {
DeviceEvent lastEvent = events.getItem(0);
gwtDevice.setLastEventType(lastEvent.getResource());
gwtDevice.setLastEventOn(lastEvent.getReceivedOn());
}
gwtDevices.add(gwtDevice);
}
} catch (Throwable t) {
KapuaExceptionHandler.handle(t);
}
gwtResults = new BasePagingLoadResult<GwtDevice>(gwtDevices);
gwtResults.setOffset(loadConfig.getOffset());
gwtResults.setTotalLength(totalResult);
return gwtResults;
}
Aggregations