1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.properties.admin.resources.share;
17
18 import java.io.IOException;
19 import java.io.OutputStream;
20 import java.io.PrintStream;
21 import java.net.URI;
22
23 import javax.inject.Inject;
24 import javax.ws.rs.ForbiddenException;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27 import javax.ws.rs.core.UriBuilder;
28 import javax.ws.rs.ext.Provider;
29
30 import de.smartics.html5.jatl.HtmlFactory;
31 import de.smartics.html5.jatl.HtmlResourceContext;
32 import de.smartics.properties.admin.resources.representation.html.share.ExceptionHtmlRepresentationRenderer;
33 import de.smartics.resteasy.hypermedia.renderer.AbstractExceptionHandler;
34 import de.smartics.resteasy.hypermedia.renderer.I18nProvider;
35 import de.smartics.resteasy.hypermedia.renderer.RepresentationRenderer;
36 import de.smartics.resteasy.hypermedia.renderer.ResourceContext;
37
38
39
40
41
42 @Provider
43 public class ExceptionHandler extends AbstractExceptionHandler
44 {
45
46
47
48
49
50
51
52
53
54 @Inject
55 protected HtmlFactory factory;
56
57
58
59
60 @Inject
61 protected I18nProvider i18nProvider;
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77 @Override
78 protected I18nProvider getI18nProvider()
79 {
80 return i18nProvider;
81 }
82
83 @Override
84 public Response toResponse(final Throwable exception)
85 {
86 if (exception instanceof ForbiddenException)
87 {
88 final String redirect =
89 request.getUri().getAbsolutePath().toASCIIString();
90 final UriBuilder builder =
91 uriInfo.getBaseUriBuilder().segment("..")
92 .queryParam("redirect-to", redirect);
93 final URI login = builder.build();
94 return Response.seeOther(login).build();
95 }
96 else
97 {
98 try
99 {
100 writeContents(exception);
101
102 return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
103 }
104 catch (final IOException e)
105 {
106 throw new IllegalStateException("Cannot write exception to response: "
107 + e.getMessage(), exception);
108 }
109 }
110 }
111
112 private void writeContents(final Throwable exception) throws IOException
113 {
114 final OutputStream entityStream = response.getOutputStream();
115
116 final ResourceContext context = createContext();
117
118 for (final MediaType contentType : request.getHttpHeaders()
119 .getAcceptableMediaTypes())
120 {
121 if (MediaType.TEXT_HTML_TYPE.isCompatible(contentType))
122 {
123 final HtmlResourceContext htmlContext =
124 new HtmlResourceContext(context, factory);
125 final RepresentationRenderer<Throwable> view =
126 new ExceptionHtmlRepresentationRenderer(htmlContext, exception,
127 entityStream);
128 view.render();
129 return;
130 }
131 }
132
133 final PrintStream print = new PrintStream(entityStream);
134 print.append(exception.toString());
135 }
136
137
138 }