package com.metrictracker.ws;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Logger;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.metrictracker.model.Metric;
import com.metrictracker.model.MetricGoal;
import com.metrictracker.model.MetricGoalDao;
import com.metrictracker.util.ExceptionManager;
/**
* Resource which has only one representation.
*
*/
public class ManageMetricGoal extends MetricTrackerServerResource {
private static final Logger log = Logger.getLogger(ManageMetricGoal.class.getName());
@Get
public String rep() {
Metric metric = getMetric();
MetricGoalDao dao = new MetricGoalDao();
Iterator<MetricGoal> metricGoals = dao.listByProperty("metricKey", metric.getKey()).iterator();
StringBuffer sb = new StringBuffer("");
sb.append("Metric Name: " + metric.getName());
sb.append(System.getProperty("line.separator"));
sb.append("Goal Name\t");
sb.append("Goal Type\t");
sb.append("Effective\t\t\t");
sb.append("Expiration\t\t\t");
sb.append("Goal");
sb.append(System.getProperty("line.separator"));
while (metricGoals.hasNext()) {
MetricGoal metricGoal = metricGoals.next();
sb.append(metricGoal.getName());
sb.append("\t");
sb.append(metricGoal.getGoalType());
sb.append("\t");
sb.append(metricGoal.getEffectivityDate());
sb.append("\t");
sb.append(metricGoal.getExpirationDate());
sb.append("\t");
sb.append(metricGoal.getGoal());
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
@Post("form:xml|json")
public void acceptRepresentation(Representation entity) throws ResourceException {
Objectify ofy = ObjectifyService.begin();
Metric metric = getMetric();
try {
HashMap<String, String> parameters = getParameters(entity);
MetricGoal metricGoal = new MetricGoal();
metricGoal.setMetric(metric);
metricGoal.setGoalType(parameters.get("goalType"));
metricGoal.setGoal(Float.valueOf(parameters.get("goal")));
metricGoal.setEffectivityDate(Date.valueOf(parameters.get("effectivityDate")));
metricGoal.setExpirationDate(Date.valueOf(parameters.get("expirationDate")));
metricGoal.setName(parameters.get("goalName"));
ofy.put(metricGoal);
getResponse().setStatus(Status.SUCCESS_CREATED);
} catch (IOException e) {
ExceptionManager.logException(log, e);
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
return;
}
}
}