Send Data to HTML Template through Spring AOP? - spring-mvc

I'd like to wrap all the controller methods using Spring AOP for Error Handling.
But, How to send e.getMessage() in catch block to ${errorMessage} in error.html properly?
Thanks for the response!
#Pointcut("within(com.test.mvc.controller.*) && #within(org.springframework.stereotype.Controller)")
public void controllerLayer() {
}
#Pointcut("execution(public String *(..))")
public void publicMethod() {
}
#Pointcut("controllerLayer() && publicMethod()")
public void controllerPublicMethod() {
}
#Around("controllerPublicMethod()")
public String processRequest(ProceedingJoinPoint joinPoint) {
try {
return (String) joinPoint.proceed();
} catch (Throwable e) {
LOGGER.info("{}", e.getMessage());
return "error.html";
}
}
<body>
<h1>Something went wrong!</h1>
<h3 th:text="'Error Message: ' + ${errorMessage}"></h3>
</body>

Following aspect can set the request attribute to display errorMessage.
#Around("controllerPublicMethod()")
public Object processRequest(ProceedingJoinPoint joinPoint) {
Object object=null;
try {
object = joinPoint.proceed();
} catch (Throwable e) {
RequestContextHolder.getRequestAttributes().setAttribute("errorMessage",e.getMessage(),0); // scope 0 - request , 1 - session
return "error.html";
}
return object;
}
I recommend you please explore the possibilities of #ControllerAdvice

Related

Android Retrofit 2.0: no response to HTTP call

I am an Android developer, I am working with Retrofit. The first day I had a response but the second day the response did not come, why I will working after I can uninstall and install the app then only it will work why, how to I resolve it please help me...
private void HomeWorks() {
HomeWorkApi homeWorkApi =
MissReportServer.getClient().create(HomeWorkApi.class);
Call<VrrittamResponse<ArrayList<HomeWork>>> call =
homeWorkApi.getHomeWork(access_token);
call.enqueue(new Callback<VrrittamResponse<ArrayList<HomeWork>>>() {
#Override
public void onResponse(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Response<VrrittamResponse<ArrayList<HomeWork>>> response) {
try {
ArrayList<HomeWork> homeWork = response.body().getContent();
if (homeWork != null && !homeWork.isEmpty()) {
recyclerView.setAdapter(new HomeWorkAdapter(homeWork,
R.layout.list_item_homework, getActivity()));
}
else {
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
catch (Exception ex){
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
#Override
public void onFailure(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Throwable t) {
Log.e("TAG",t.getMessage());
ExceptionHandle.alertDialogShow(getActivity());
}
});
}

When does HttpContext.AllErrors contain more than one exception?

In an ASP.NET application typical error handling code involves some variation of GetLastError(), however there's also HttpContext.AllErrors collection of which the GetLastError() method only retrieves the first one. What are the scenarios where the AllErrors collection might contain more than 1 exception? I cannot think of anything, but obviously it's there for a purpose...
The ASP.NET Framework supports a different model where a request can encounter multiple errors, all of which can be reported without stopping request processing, allowing for more nuanced and useful information to be presented to the user.
namespace ErrorHandling
{
// sample class adding errors to HttpContext
public partial class SumControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int? first = GetIntValue("first");
int? second = GetIntValue("second");
if (first.HasValue && second.HasValue)
{
//result.InnerText = (first.Value + second.Value).ToString();
//resultPlaceholder.Visible = true;
}
else
{
Context.AddError(new Exception("Cannot perform calculation"));
}
}
}
private int? GetIntValue(string name)
{
int value;
if (Request[name] == null)
{
Context.AddError(new ArgumentNullException(name));
return null;
}
else if (!int.TryParse(Request[name], out value))
{
Context.AddError(new ArgumentOutOfRangeException(name));
return null;
}
return value;
}
}
}
// intercepting the errors
public class Global : System.Web.HttpApplication
{
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Context.AllErrors != null && Context.AllErrors.Length > 1)
{
Response.ClearHeaders();
Response.ClearContent();
Response.StatusCode = 200;
Server.Execute("/MultipleErrors.aspx");
Context.ClearError();
}
}
}
// MultipleErrors code behind
public partial class MultipleErrors : System.Web.UI.Page
{
public IEnumerable<string> GetErrorMessages()
{
return Context.AllErrors.Select(e => e.Message);
}
}
The answer is heavily referencing pro asp.net 4.5 from appress

GWT: unable to access xml

I'm trying to access a XML file from client side in GWT. But it looks like the sendRequest method is not getting fired at all.
I'm able to see the xml in the browser. Do I need to do any thing in the server side?
Any help is appreciated.
Here's my code
String xmlurl = "http://localhost:8888/test.xml";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(xmlurl));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
System.out.println(exception);
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
System.out.println(response.getText());
} else {
System.out.println(response.getStatusCode());
}
}
});
} catch (RequestException e) {
System.out.println("exception"+e);
}
I tried the following code too, but have the same problem. The developer tool shows response status as 200 and correct response text. Only, its not working in the code.
String xmlurl = "http://127.0.0.1:8888/test.xml";
httpGetFile(xmlurl, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
xmlData = "Error";
}
public void onSuccess(String xmlText) {
xmlData = xmlText;
}
});
public static void httpGetFile(final String url, final AsyncCallback<String> callback) {
final RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
rb.setCallback(new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
try {
System.out.println("dafadfdf");
final int responseCode = response.getStatusCode() / 100;
if (url.startsWith("file:/") || (responseCode == 2)) {
callback.onSuccess(response.getText());
} else {
callback.onFailure(new IllegalStateException("HttpError#" + response.getStatusCode() + " - " + response.getStatusText()));
}
} catch (Throwable e) {
callback.onFailure(e);
}
}
public void onError(Request request, Throwable exception) {
callback.onFailure(exception);
}
});
try {
rb.send();
} catch (RequestException e) {
callback.onFailure(e);
}
}
Always Use logging instead of System.out.print statements https://developers.google.com/web-toolkit/doc/latest/DevGuideLogging
Step 1 - Add logging statements to failure, success and try catch statements. Clean up the exception.
Step 2 - "Parsing the XML" should be done inside the "onSuccess" method of the rb callback.
You do not need a RequestBuilder at all to access an XML file. You can use an ExternalTextResource for this:
https://developers.google.com/web-toolkit/doc/latest/DevGuideClientBundle#TextResource

JFace button in TableViewerColumn

Is it possible to have a button in a TableViewerColumn? There are several posts that confirm this, but I've found no code that actually works. I've read about a DialogCellEditor, too, is that what to look into?
Regards,
Marcus
As this seems to be a common problem, I've tried a workaround. I use an image as label and add editing support like so:
col = createTableViewerColumn(titles[10], bounds[10], 10);
col.setEditingSupport(new DeleteSupport(viewer));
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public Image getImage(Object element) {
return new Image(ApplicationRunner.getApp().getShell()
.getDisplay(), "ressources/images/delete.png");
}
#Override
public String getText(Object element) {
return "";
}
});
In the DeleteSupport class (extending EditingSupport), you have to let canEdit() return false, so the image is not selectable. But then, you can't work with getValue(). So, I do whatever I have to in canEdit() BEFORE returning false. That's the same behavior as a simple push button would have.
The DeleteSupport looks like this:
public class DeleteSupport extends EditingSupport {
private final TableViewer viewer;
public DeleteSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
#Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor(viewer.getTable());
}
#Override
protected boolean canEdit(Object element) {
// if confirmed, try to delete the customer
if (MessageDialog.openConfirm( ApplicationRunner.getApp().getShell(),
"Confirm delete",
"Soll " + ((Customer) element).getFirstname()
+ " " + ((Customer) element).getLastname()
+ " be deleted? Cannot be undone!")) {
try {
CustomerDAO.getInstance().delete(((Customer) element).getId());
} catch (SQLException e) {
// TODO something
}
}
// reload anyways
try {
viewer.setInput(CustomerDAO.getInstance().getAll());
} catch (SQLException e) {
// TODO something else
}
viewer.refresh();
return false;
}
#Override
protected Object getValue(Object element) {
return "";
}
#Override
protected void setValue(Object element, Object value) {
}
}

How to use System.Action with return type?

In the BLL class, I have written:
Private List<T> GetData(string a, string b)
{
TryAction(()=>{
//Call BLL Method to retrieve the list of BO.
return BLLInstance.GetAllList(a,b);
});
}
In the BLL Base Class, I have a method:
protected void TryAction(Action action)
{
try
{
action();
}
catch(Exception e)
{
// write exception to output (Response.Write(str))
}
}
How can I use TryAction() method with generic return type?
please have a suggestion.
You need to use Func to represent a method which will return a value.
Below is an example
private List<int> GetData(string a, string b)
{
return TryAction(() =>
{
//Call BLL Method to retrieve the list of BO.
return BLLInstance.GetAllList(a,b);
});
}
protected TResult TryAction<TResult>(Func<TResult> action)
{
try
{
return action();
}
catch (Exception e)
{
throw;
// write exception to output (Response.Write(str))
}
}
Action is a delegate that has a void return type, so if you want it to return a value, you can't.
For that, you need to use a Func delegate (there are many - the last type parameter is the return type).
If you simply want to have TryAction return a generic type, make it into a generic method:
protected T TryAction<T>(Action action)
{
try
{
action();
}
catch(Exception e)
{
// write exception to output (Response.Write(str))
}
return default(T);
}
Depending on what exactly you are trying to do, you may need to use both a generic method and Func delegate:
protected T TryAction<T>(Func<T> action)
{
try
{
return action();
}
catch(Exception e)
{
// write exception to output (Response.Write(str))
}
return default(T);
}
You should consider to use Func delegate instead of Action delegate.

Resources