001: package org.vraptor.view;
002:
003: import java.io.IOException;
004:
005: import javax.servlet.ServletException;
006:
007: import org.apache.log4j.Logger;
008: import org.vraptor.LogicRequest;
009:
010: /**
011: * Regex based view manager.
012: *
013: * @author Guilherme Silveira
014: */
015: public class RegexViewManager implements ViewManager {
016:
017: private static final Logger LOG = Logger
018: .getLogger(RegexViewManager.class);
019:
020: private final String replacement;
021:
022: private final String regex = ("(.*);(.*);(.*)");
023:
024: /**
025: * Instantiates the regex view manager with this replacement string.
026: *
027: * @param replacement
028: * the replacement string
029: */
030: public RegexViewManager(String replacement) {
031:
032: this .replacement = translateExpression(replacement);
033: }
034:
035: /**
036: * Method replaces any $component with $1, $logic with $2 and $result with
037: * $3 within the string.
038: *
039: * @param replacement
040: * the string to replace
041: * @return the translated string
042: */
043: String translateExpression(String replacement) {
044: if (replacement != null
045: && replacement
046: .matches(".*(\\$component|\\$logic|\\$result).*")) {
047: replacement = replacement
048: .replaceAll("\\$component", "\\$1").replaceAll(
049: "\\$logic", "\\$2").replaceAll("\\$result",
050: "\\$3");
051: }
052: return replacement;
053: }
054:
055: /**
056: *
057: * @see org.vraptor.view.ViewManager#getForward(org.vraptor.LogicRequest,
058: * java.lang.String)
059: */
060: private String getForward(LogicRequest request, String result)
061: throws ViewException {
062: String value = request.getRequestInfo().getComponentName()
063: + ";" + request.getRequestInfo().getLogicName() + ";"
064: + result;
065: return value.replaceAll(regex, replacement);
066:
067: }
068:
069: public void forward(LogicRequest logicRequest, String result)
070: throws ViewException {
071: String forward = getForward(logicRequest, result);
072: directForward(logicRequest, result, forward);
073: }
074:
075: public void directForward(LogicRequest logicRequest, String result,
076: String forwardUrl) throws ViewException {
077: LOG.debug("Server-side redirect to: " + forwardUrl);
078: try {
079: logicRequest.getRequest().getRequestDispatcher(forwardUrl)
080: .forward(logicRequest.getRequest(),
081: logicRequest.getResponse());
082: } catch (ServletException ex) {
083: if (ex.getCause() != null) {
084: throw new ViewException(ex.getCause());
085: }
086: throw new ViewException(ex);
087: } catch (IOException ex) {
088: throw new ViewException(ex);
089: }
090: }
091:
092: public void redirect(LogicRequest logicRequest, String url)
093: throws ViewException {
094: LOG.debug("Client-side redirect to: " + url);
095: try {
096: logicRequest.getResponse().sendRedirect(url);
097: } catch (IOException e) {
098: throw new ViewException(e);
099: }
100: }
101:
102: }
|