001 package org.hackystat.sensorbase.resource.db; 002 003 import org.hackystat.sensorbase.db.DbManager; 004 import org.hackystat.sensorbase.resource.sensorbase.SensorBaseResource; 005 import org.restlet.Context; 006 import org.restlet.data.Request; 007 import org.restlet.data.Response; 008 import org.restlet.resource.Representation; 009 import org.restlet.resource.StringRepresentation; 010 import org.restlet.resource.Variant; 011 012 /** 013 * Implements the resource for obtaining the number of rows in a specifed table using 014 * GET {host}/db/table/{table}/rowcount. 015 * @author Philip Johnson 016 */ 017 public class RowCountResource extends SensorBaseResource { 018 019 /** Holds the table name passed in the request. */ 020 private String table; 021 022 /** 023 * The standard constructor. 024 * 025 * @param context The context. 026 * @param request The request object. 027 * @param response The response object. 028 */ 029 public RowCountResource(Context context, Request request, Response response) { 030 super(context, request, response); 031 this.table = (String) request.getAttributes().get("table"); 032 } 033 034 /** 035 * Returns the row count for the specifed table, or an error if the user is not the admin or 036 * the table name is not valid. 037 * @param variant Ignored. 038 * @return The row count as a string. 039 */ 040 @Override 041 public Representation represent(Variant variant) { 042 try { 043 if (!validateAuthUserIsAdmin()) { 044 return null; 045 } 046 047 DbManager dbManager = (DbManager) this.server.getContext().getAttributes().get("DbManager"); 048 int rowCount = dbManager.getRowCount(table); 049 // If rowCount is negative, then that means the table name was invalid. 050 if (rowCount == -1) { 051 setStatusMiscError("Invalid Table Name"); 052 return null; 053 } 054 // Otherwise return the row count as a string. 055 return new StringRepresentation(String.valueOf(rowCount)); 056 } 057 catch (RuntimeException e) { 058 setStatusInternalError(e); 059 } 060 return null; 061 } 062 }