1 package org.jcr_blog.commons;
2
3 import java.io.IOException;
4 import java.util.Locale;
5 import java.util.MissingResourceException;
6 import java.util.ResourceBundle;
7 import javax.faces.application.NavigationHandler;
8 import javax.faces.context.FacesContext;
9 import javax.servlet.http.HttpServletResponse;
10
11
12
13
14
15 public final class JSFUtils {
16
17 public enum StatusCode {
18
19 FORBIDDEN(HttpServletResponse.SC_FORBIDDEN),
20 NOT_FOUND(HttpServletResponse.SC_NOT_FOUND),
21 BAD_REQUEST(HttpServletResponse.SC_BAD_REQUEST);
22 private int code;
23
24 private StatusCode(final int code) {
25 this.code = code;
26 }
27
28 public int getCode() {
29 return code;
30 }
31
32 @Override
33 public String toString() {
34 return String.valueOf(this.code);
35 }
36 }
37 private static final String RESOURCE_BUNDLE = "org.jcr_blog.messages";
38
39
40
41
42 private JSFUtils() {
43 throw new AssertionError();
44 }
45
46
47
48
49
50
51 public static void sendStatusCode(final StatusCode code) throws IOException {
52 sendStatusCode(code, null);
53 }
54
55
56
57
58
59
60
61 public static void sendStatusCode(final StatusCode code, final String message) throws IOException {
62 final FacesContext ctx = FacesContext.getCurrentInstance();
63 HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
64
65 if (message == null) {
66 response.sendError(code.getCode());
67 } else {
68 response.sendError(code.getCode(), message);
69 }
70
71 ctx.responseComplete();
72 }
73
74
75
76
77
78
79 @Deprecated
80 public static void redirect(final String page) {
81 final FacesContext ctx = FacesContext.getCurrentInstance();
82 final NavigationHandler nav = ctx.getApplication().getNavigationHandler();
83 nav.handleNavigation(ctx, null, page + "?faces-redirect=true&includeViewParams=true");
84 }
85
86 public static String getMessage(final String key, final String... params) {
87 final FacesContext ctx = FacesContext.getCurrentInstance();
88
89
90 ResourceBundle bundle = ctx.getApplication().getResourceBundle(ctx, RESOURCE_BUNDLE);
91 if (bundle == null) {
92 final Locale locale = ctx.getViewRoot().getLocale();
93 bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE, locale);
94 }
95 try {
96 String result = bundle.getString(key);
97
98 for (int i = 0; i < params.length; i++) {
99 result = result.replaceAll("\\{" + i + "\\}", String.valueOf(params[i]));
100 }
101 return result;
102 } catch (MissingResourceException ex) {
103 return "???" + key + "???";
104 }
105 }
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120 }