service.database.command.DeleteDatabaseRow Maven / Gradle / Ivy
package service.database.command;
import com.google.gson.Gson;
import databaseconnector.api.Column;
import databaseconnector.api.DatabaseConnection;
import databaseconnector.api.sql.SQLDatabaseConnection;
import databaseconnector.api.sql.SQLTable;
import service.database.exception.*;
import service.exception.InvalidRequestDataException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
public class DeleteDatabaseRow extends AbstractDatabaseCommand {
public static class RequestData{
private String table;
private Map values;
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public Map getValues() {
return values;
}
public void setValues(Map values) {
this.values = values;
}
}
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doOptions(req, resp);
setAccessControlAllowOriginHeader(req, resp);
resp.setHeader("Access-Control-Allow-Methods", "DELETE");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
setAccessControlAllowOriginHeader(req, resp);
try {
checkDatabaseInitiated();
RequestData requestData = new Gson().fromJson(req.getReader(), RequestData.class);
if (requestData == null){
throw new InvalidRequestDataException("Request body is empty or has an invalid format");
}
SQLTable table = getTableParameter(requestData.getTable());
Map values = getColumnValuesParameter(requestData.getValues(), table);
SQLDatabaseConnection databaseConnection = getDatabaseConnection();
databaseConnection.delete(new RowMatcher(values, table));
resp.setStatus(200);
} catch (DatabaseRoleNotActivatedException exception) {
displayError(resp, 501, exception.getMessage());
} catch (InvalidRequestDataException | UnknownTableException | ColumnNotExistsException | EmptyRecordException exception) {
displayError(resp, 400, exception.getMessage());
} catch (DatabaseNotInitiatedException exception) {
displayError(resp, 500, exception.getMessage());
}
}
}