service.database.command.UpdateDatabaseRow 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 UpdateDatabaseRow extends AbstractDatabaseCommand {
public static class RequestData{
private String table;
private Map oldRow;
private Map newRow;
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public Map getOldRow() {
return oldRow;
}
public void setOldRow(Map oldRow) {
this.oldRow = oldRow;
}
public Map getNewRow() {
return newRow;
}
public void setNewRow(Map newRow) {
this.newRow = newRow;
}
}
@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 oldValues = getColumnValuesParameter(requestData.getOldRow(), table);
Map new_values = getColumnValuesParameter(requestData.getNewRow(), table);
SQLDatabaseConnection.Row newRowValues = new SQLDatabaseConnection.Row(new_values, table);
SQLDatabaseConnection databaseConnection = getDatabaseConnection();
databaseConnection.update(newRowValues, new RowMatcher(oldValues, 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());
}
}
}