public WOResponse nullResponse() {
   if (nullResponse == null) {
     nullResponse = Application.app().createResponseInContext(null);
     nullResponse.setStatus(500);
     nullResponse.appendContentString(
         "<html><head><title>Errorlt;/title></head><body>Votre requ�te produit une erreur.</body></html>");
   }
   return nullResponse;
 }
 @Override
 public void appendToResponse(WOResponse r, WOContext c) {
   if (session().objectForKey("ERXDatabaseConsole.enabled") != null) {
     super.appendToResponse(r, c);
   } else {
     r.appendContentString("please use the ERXDirectAction databaseConsoleAction to login first!");
   }
 }
 protected WOResponse _generateResponseForInputStream(InputStream is, long length, String type) {
   WOResponse response = application.createResponseInContext(null);
   if (is != null) {
     if (length != 0) {
       response.setContentStream(is, 50 * 1024, length);
     }
   } else {
     response.setStatus(404);
   }
   if (type != null) {
     response.setHeader(type, "content-type");
   }
   if (length != 0) {
     response.setHeader("" + length, "content-length");
   }
   return response;
 }
 public WOActionResults inscrire() {
   ERXRedirect redirectPage = null;
   NouveauDossierPreEtudiant page =
       (NouveauDossierPreEtudiant)
           component.pageWithName(NouveauDossierPreEtudiant.class.getName());
   try {
     page.ctrl.initDossier(unPreEtudiant());
     redirectPage = new ERXRedirect(component.context());
     redirectPage.setComponent(page);
     component.session().setErreur(null);
   } catch (CtrlInscriptionException e) {
     component.session().defaultEditingContext().revert();
     component.session().defaultEditingContext().invalidateAllObjects();
     WOResponse response = new WOResponse();
     response.setStatus(500);
     component.session().setErreur(e.getMessageJS());
     return response;
   }
   return redirectPage;
 }
Beispiel #5
0
  protected void _appendValueAttributeToResponse(WOResponse woresponse, WOContext wocontext) {
    WOComponent component = wocontext.component();

    Object valueInComponent = _value.valueInComponent(component);
    if (valueInComponent != null) {
      String stringValue = valueInComponent.toString();
      woresponse._appendTagAttributeAndValue("value", stringValue, true);
    }

    if (_size != null) {
      Object sizeInComponent = _size.valueInComponent(component);
      if (sizeInComponent != null) {
        String stringValue = sizeInComponent.toString();
        woresponse._appendTagAttributeAndValue("size", stringValue, true);
      }
    }

    if (_maxlength != null) {
      Object maxlengthInComponent = _maxlength.valueInComponent(component);
      if (maxlengthInComponent != null) {
        String stringValue = maxlengthInComponent.toString();
        woresponse._appendTagAttributeAndValue("maxlength", stringValue, true);
      }
    }

    if (_placeholder != null) {
      Object placeholderInComponent = _placeholder.valueInComponent(component);
      if (placeholderInComponent != null) {
        String stringValue = placeholderInComponent.toString();
        woresponse._appendTagAttributeAndValue("placeholder", stringValue, true);
      }
    }

    if (_pattern != null) {
      Object patternInComponent = _pattern.valueInComponent(component);
      if (patternInComponent != null) {
        String stringValue = patternInComponent.toString();
        woresponse._appendTagAttributeAndValue("pattern", stringValue, true);
      }
    } else {
      woresponse._appendTagAttributeAndValue("pattern", EMAIL_PATTERN, true);
    }

    if (isRequiredInContext(wocontext)) {
      woresponse._appendTagAttributeAndValue("required", "required", false);
    }

    if (isReadonlyInContext(wocontext)) {
      woresponse._appendTagAttributeAndValue("readonly", "readonly", false);
    }
  }
 public void appendAttributesToResponse(WOResponse response, WOContext context) {
   WOComponent component = context.component();
   String href;
   if (_href != null) {
     href = (String) _href.valueInComponent(component);
   } else {
     String framework = "app";
     if (_framework != null) {
       Object val = _framework.valueInComponent(component);
       if (val != null) {
         framework = val.toString();
       }
     }
     String filename = (String) _filename.valueInComponent(component);
     WOResourceManager rs = WOApplication.application().resourceManager();
     href = rs.urlForResourceNamed(filename, framework, null, context.request());
   }
   response._appendTagAttributeAndValue("href", href, false);
   response._appendTagAttributeAndValue("rel", "SHORTCUT ICON", false);
   super.appendAttributesToResponse(response, context);
 }
Beispiel #7
0
  /**
   * Overridden to get use apply the XLST transformation on the content.
   *
   * @throws TransformerException
   */
  public void appendToResponse(WOResponse response, WOContext context) {
    start = System.currentTimeMillis();
    current = start;
    if (isEnabled()) {
      WOResponse newResponse = new WOResponse();
      newResponse.setContentEncoding(response.contentEncoding());

      super.appendToResponse(newResponse, context);

      if (log.isDebugEnabled()) {
        String contentString = newResponse.contentString();
        log.debug("Converting content string:\n" + contentString);
      }

      try {
        NSData data = transform(transformer(), newResponse.content());
        if (hasBinding("data") && canSetValueForBinding("data")) {
          setValueForBinding(data, "data");
        }
        if (hasBinding("stream") && canSetValueForBinding("stream")) {
          setValueForBinding(data.stream(), "stream");
        }
        response.appendContentData(data);
      } catch (TransformerException e) {
        throw NSForwardException._runtimeExceptionForThrowable(e);
      }
    } else {
      super.appendToResponse(response, context);
    }
    log.debug("Total: " + (System.currentTimeMillis() - start));
    start = System.currentTimeMillis();
  }
  /**
   * Generate a link that opens the indicated dialog.
   *
   * @see er.ajax.AjaxComponent#appendToResponse(com.webobjects.appserver.WOResponse,
   *     com.webobjects.appserver.WOContext)
   */
  @Override
  public void appendToResponse(WOResponse response, WOContext context) {
    if (!booleanValueForBinding("enabled", true)) {
      return;
    }

    String elementName = (String) valueForBinding("elementName", "a", context.component());

    response.appendContentString("<" + elementName + " ");

    if (elementName.equals("a")) {
      response.appendContentString("href=\"javascript:void(0)\"");
      appendTagAttributeToResponse(response, "title", valueForBinding("linkTitle", null));
    }

    appendTagAttributeToResponse(response, "id", id());
    appendTagAttributeToResponse(response, "class", valueForBinding("class", null));
    appendTagAttributeToResponse(response, "style", valueForBinding("style", null));

    // onclick calls the script that opens the AjaxModalDialog
    response.appendContentString(" onclick=\"");

    response.appendContentString("new Ajax.Request('");
    response.appendContentString(AjaxUtils.ajaxComponentActionUrl(context()));
    response.appendContentString("', ");
    AjaxOptions.appendToResponse(ajaxRequestOptions(), response, context);
    response.appendContentString("); ");

    response.appendContentString("return false;\" >");

    if (elementName.equals("a") && hasBinding("label")) {
      response.appendContentString((String) valueForBinding("label"));
    } else {
      // This will append the contents inside of the link
      super.appendToResponse(response, context);
    }

    response.appendContentString("</" + elementName + ">");
  }
 public WOResponse generateRequestRefusal(WORequest aRequest) {
   WODynamicURL aURIString = aRequest._uriDecomposed();
   String contentString =
       (new StringBuilder())
           .append(
               "D�sol�, votre demande n'a pas pu �tre imm�diatement trait�es. S'il vous pla�t essayer cette URL: <a href=\"")
           .append(aURIString)
           .append("\">")
           .append(aURIString)
           .append("</a>")
           .toString();
   aURIString.setApplicationNumber("-1");
   WOResponse aResponse = WOApplication.application().createResponseInContext(null);
   WOResponse._redirectResponse(aResponse, aURIString.toString(), contentString);
   return aResponse;
 }
  @SuppressWarnings("unchecked")
  @Override
  public WOResponse handleRequest(WORequest request) {
    WOApplication application = WOApplication.application();
    application.awake();
    try {
      WOContext context = application.createContextForRequest(request);
      WOResponse response = application.createResponseInContext(context);

      Object output;
      try {
        String inputString = request.contentString();
        JSONObject input = new JSONObject(inputString);
        String wosid = request.cookieValueForKey("wosid");
        if (wosid == null) {
          ERXMutableURL url = new ERXMutableURL();
          url.setQueryParameters(request.queryString());
          wosid = url.queryParameter("wosid");
          if (wosid == null && input.has("wosid")) {
            wosid = input.getString("wosid");
          }
        }
        context._setRequestSessionID(wosid);
        WOSession session = null;
        if (context._requestSessionID() != null) {
          session = WOApplication.application().restoreSessionWithID(wosid, context);
        }
        if (session != null) {
          session.awake();
        }
        try {
          JSONComponentCallback componentCallback = null;

          ERXDynamicURL url = new ERXDynamicURL(request._uriDecomposed());
          String requestHandlerPath = url.requestHandlerPath();
          JSONRPCBridge jsonBridge;
          if (requestHandlerPath != null && requestHandlerPath.length() > 0) {
            String componentNameAndInstance = requestHandlerPath;
            String componentInstance;
            String componentName;
            int slashIndex = componentNameAndInstance.indexOf('/');
            if (slashIndex == -1) {
              componentName = componentNameAndInstance;
              componentInstance = null;
            } else {
              componentName = componentNameAndInstance.substring(0, slashIndex);
              componentInstance = componentNameAndInstance.substring(slashIndex + 1);
            }

            if (session == null) {
              session = context.session();
            }

            String bridgesKey =
                (componentInstance == null) ? "_JSONGlobalBridges" : "_JSONInstanceBridges";
            Map<String, JSONRPCBridge> componentBridges =
                (Map<String, JSONRPCBridge>) session.objectForKey(bridgesKey);
            if (componentBridges == null) {
              int limit =
                  ERXProperties.intForKeyWithDefault(
                      (componentInstance == null)
                          ? "er.ajax.json.globalBacktrackCacheSize"
                          : "er.ajax.json.backtrackCacheSize",
                      WOApplication.application().pageCacheSize());
              componentBridges = new LRUMap<String, JSONRPCBridge>(limit);
              session.setObjectForKey(componentBridges, bridgesKey);
            }
            jsonBridge = componentBridges.get(componentNameAndInstance);
            if (jsonBridge == null) {
              Class componentClass = _NSUtilities.classWithName(componentName);
              JSONComponent component;
              if (JSONComponent.class.isAssignableFrom(componentClass)) {
                component =
                    (JSONComponent)
                        _NSUtilities.instantiateObject(
                            componentClass,
                            new Class[] {WOContext.class},
                            new Object[] {context},
                            true,
                            false);
              } else {
                throw new SecurityException(
                    "There is no JSON component named '" + componentName + "'.");
              }
              jsonBridge =
                  createBridgeForComponent(
                      component, componentName, componentInstance, componentBridges);
            }

            componentCallback = new JSONComponentCallback(context);
            jsonBridge.registerCallback(componentCallback, WOContext.class);
          } else {
            jsonBridge = _sharedBridge;
          }

          try {
            output = jsonBridge.call(new Object[] {request, response, context}, input);
          } finally {
            if (componentCallback != null) {
              jsonBridge.unregisterCallback(componentCallback, WOContext.class);
            }
          }

          if (context._session() != null) {
            WOSession contextSession = context._session();
            // If this is a new session, then we have to force it to be a cookie session
            if (wosid == null) {
              boolean storesIDsInCookies = contextSession.storesIDsInCookies();
              try {
                contextSession.setStoresIDsInCookies(true);
                contextSession._appendCookieToResponse(response);
              } finally {
                contextSession.setStoresIDsInCookies(storesIDsInCookies);
              }
            } else {
              contextSession._appendCookieToResponse(response);
            }
          }
          if (output != null) {
            response.appendContentString(output.toString());
          }

          if (response != null) {
            response._finalizeInContext(context);
            response.disableClientCaching();
          }
        } finally {
          try {
            if (session != null) {
              session.sleep();
            }
          } finally {
            if (context._session() != null) {
              WOApplication.application().saveSessionForContext(context);
            }
          }
        }
      } catch (NoSuchElementException e) {
        e.printStackTrace();
        output =
            new JSONRPCResult(
                JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD);
      } catch (JSONException e) {
        e.printStackTrace();
        output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
      } catch (Throwable t) {
        t.printStackTrace();
        output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, t.getMessage());
      }

      return response;
    } finally {
      application.sleep();
    }
  }
  // @Override
  public WOResponse handleRequest(WORequest request) {
    if (!ERSelenium.testsEnabled()) {
      return new WOResponse();
    }

    NSArray pathElements = request.requestHandlerPathArray();

    StringBuilder builder = new StringBuilder();
    Iterator iter = pathElements.iterator();
    while (iter.hasNext()) {
      builder.append(iter.next());
      if (iter.hasNext()) builder.append("/");
    }

    String filePath = builder.toString();
    log.debug("Processing file '" + filePath + "'");

    /*
     * Syncrhonization mistakes are possible here, but not fatal at all.
     * At the worst case the file will be read 2-or-more times instead of 1 (if process 1
     * checks that the file is not cached and process 2 does the same check before
     * process 1 has updated the cache).
     */

    CachedFile cachedFile;
    synchronized (_cache) {
      cachedFile = (CachedFile) _cache.objectForKey(filePath);
    }

    if (cachedFile == null) {
      cachedFile = new CachedFile();

      URL fileUrl =
          WOApplication.application()
              .resourceManager()
              .pathURLForResourceNamed(filePath, "ERSelenium", null);
      if (fileUrl == null) {
        throw new RuntimeException("Can't find specified resource ('" + filePath + "')");
      }
      cachedFile.mimeType =
          WOApplication.application().resourceManager().contentTypeForResourceNamed(filePath);
      if (cachedFile.mimeType == null) {
        throw new RuntimeException("Can't determine resource mime type ('" + filePath + "')");
      }

      try {
        cachedFile.data = new NSData(ERXFileUtilities.bytesFromInputStream(fileUrl.openStream()));
      } catch (Exception e) {
        throw new RuntimeException("Error reading file '" + fileUrl.getPath() + "'", e);
      }

      synchronized (_cache) {
        _cache.setObjectForKey(cachedFile, filePath);
      }
    }

    WOResponse response = new WOResponse();
    response.setHeader(cachedFile.mimeType, "content-type");
    response.setContent(cachedFile.data);

    NSNotificationCenter.defaultCenter()
        .postNotification(WORequestHandler.DidHandleRequestNotification, response);
    return response;
  }
  @Override
  public WOResponse handleRequest(WORequest request) {
    int bufferSize = 16384;

    WOApplication application = WOApplication.application();
    application.awake();
    try {
      WOContext context = application.createContextForRequest(request);
      WOResponse response = application.createResponseInContext(context);

      String sessionIdKey = application.sessionIdKey();
      String sessionId = (String) request.formValueForKey(sessionIdKey);
      if (sessionId == null) {
        sessionId = request.cookieValueForKey(sessionIdKey);
      }
      context._setRequestSessionID(sessionId);
      if (context._requestSessionID() != null) {
        application.restoreSessionWithID(sessionId, context);
      }

      try {
        final WODynamicURL url = request._uriDecomposed();
        final String requestPath = url.requestHandlerPath();
        final Matcher idMatcher = Pattern.compile("^id/(\\d+)/").matcher(requestPath);

        final Integer requestedAttachmentID;
        String requestedWebPath;

        final boolean requestedPathContainsAnAttachmentID = idMatcher.find();
        if (requestedPathContainsAnAttachmentID) {
          requestedAttachmentID = Integer.valueOf(idMatcher.group(1));
          requestedWebPath = idMatcher.replaceFirst("/");
        } else {
          // MS: This is kind of goofy because we lookup by path, your web path needs to
          // have a leading slash on it.
          requestedWebPath = "/" + requestPath;
          requestedAttachmentID = null;
        }

        try {
          InputStream attachmentInputStream;
          String mimeType;
          String fileName;
          long length;
          String queryString = url.queryString();
          boolean proxyAsAttachment =
              (queryString != null && queryString.contains("attachment=true"));

          EOEditingContext editingContext = ERXEC.newEditingContext();
          editingContext.lock();

          try {
            ERAttachment attachment =
                fetchAttachmentFor(editingContext, requestedAttachmentID, requestedWebPath);

            if (_delegate != null && !_delegate.attachmentVisible(attachment, request, context)) {
              throw new SecurityException("You are not allowed to view the requested attachment.");
            }
            mimeType = attachment.mimeType();
            length = attachment.size().longValue();
            fileName = attachment.originalFileName();
            ERAttachmentProcessor<ERAttachment> attachmentProcessor =
                ERAttachmentProcessor.processorForType(attachment);
            if (!proxyAsAttachment) {
              proxyAsAttachment = attachmentProcessor.proxyAsAttachment(attachment);
            }
            InputStream rawAttachmentInputStream =
                attachmentProcessor.attachmentInputStream(attachment);
            attachmentInputStream = new BufferedInputStream(rawAttachmentInputStream, bufferSize);
          } finally {
            editingContext.unlock();
          }

          response.setHeader(mimeType, "Content-Type");
          response.setHeader(String.valueOf(length), "Content-Length");

          if (proxyAsAttachment) {
            response.setHeader("attachment; filename=\"" + fileName + "\"", "Content-Disposition");
          }

          response.setStatus(200);
          response.setContentStream(attachmentInputStream, bufferSize, length);
        } catch (SecurityException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(403);
        } catch (NoSuchElementException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(404);
        } catch (FileNotFoundException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(404);
        } catch (IOException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(500);
        }

        return response;
      } finally {
        if (context._requestSessionID() != null) {
          WOApplication.application().saveSessionForContext(context);
        }
      }
    } finally {
      application.sleep();
    }
  }
  public WOResponse handleRequest(WORequest request) {
    WOResponse response = null;
    FileInputStream is = null;
    long length = 0;
    String contentType = null;
    String uri = request.uri();
    if (uri.charAt(0) == '/') {
      WOResourceManager rm = application.resourceManager();
      String documentRoot = documentRoot();
      File file = null;
      StringBuffer sb = new StringBuffer(documentRoot.length() + uri.length());
      String wodataKey = request.stringFormValueForKey("wodata");
      if (uri.startsWith("/cgi-bin") && wodataKey != null) {
        uri = wodataKey;
        if (uri.startsWith("file:")) {
          // remove file:/
          uri = uri.substring(5);
        } else {

        }
      } else {
        int index = uri.indexOf("/wodata=");

        if (index >= 0) {
          uri = uri.substring(index + "/wodata=".length());
        } else {
          sb.append(documentRoot);
        }
      }

      if (_useRequestHandlerPath) {
        try {
          WODynamicURL dynamicURL = new WODynamicURL(uri);
          String requestHandlerPath = dynamicURL.requestHandlerPath();
          if (requestHandlerPath == null || requestHandlerPath.length() == 0) {
            sb.append(uri);
          } else {
            sb.append("/");
            sb.append(requestHandlerPath);
          }
        } catch (Exception e) {
          throw new RuntimeException("Failed to parse URL '" + uri + "'.", e);
        }
      } else {
        sb.append(uri);
      }

      String path = sb.toString();
      try {
        path = path.replaceAll("\\?.*", "");
        if (request.userInfo() != null && !request.userInfo().containsKey("HttpServletRequest")) {
          /* PATH_INFO is already decoded by the servlet container */
          path = path.replace('+', ' ');
          path = URLDecoder.decode(path, CharEncoding.UTF_8);
        }
        file = new File(path);
        length = file.length();
        is = new FileInputStream(file);

        contentType = rm.contentTypeForResourceNamed(path);
        log.debug("Reading file '" + file + "' for uri: " + uri);
      } catch (IOException ex) {
        if (!uri.toLowerCase().endsWith("/favicon.ico")) {
          log.info("Unable to get contents of file '" + file + "' for uri: " + uri);
        }
      }
    } else {
      log.error("Can't fetch relative path: " + uri);
    }
    response = _generateResponseForInputStream(is, length, contentType);
    NSNotificationCenter.defaultCenter()
        .postNotification(WORequestHandler.DidHandleRequestNotification, response);
    response._finalizeInContext(null);
    return response;
  }
Beispiel #14
0
 public static WOActionResults exportJournalZPU(
     NSArray journal, WOContext context, String filename) {
   WOSession ses = context.session();
   if (journal == null || journal.count() == 0) {
     WOResponse response = WOApplication.application().createResponseInContext(context);
     response.appendContentString(
         (String) ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Tabel.noData"));
     response.setHeader("application/octet-stream", "Content-Type");
     response.setHeader("attachment; filename=\"noData.txt\"", "Content-Disposition");
     return response;
   }
   Export export = new ExportCSV(context, filename);
   export.beginRow();
   export.addValue(ses.valueForKeyPath("strings.Reusables_Strings.dataTypes.Date"));
   export.addValue(ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.OrigTeacher"));
   export.addValue(ses.valueForKeyPath("strings.RujelInterfaces_Names.EduCycle.subject"));
   export.addValue(ses.valueForKeyPath("strings.RujelInterfaces_Names.EduGroup.this"));
   export.addValue(ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Reason.Reason"));
   export.addValue(ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Reason.verification"));
   export.addValue(
       ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Substitute.Substitutor"));
   export.addValue(ses.valueForKeyPath("strings.RujelInterfaces_Names.EduCycle.subject"));
   export.addValue(ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Substitute.factor"));
   Enumeration enu = journal.objectEnumerator();
   StringBuilder buf = new StringBuilder();
   while (enu.hasMoreElements()) {
     NSDictionary dict = (NSDictionary) enu.nextElement();
     export.beginRow();
     export.addValue(MyUtility.dateFormat().format(dict.valueForKey("date")));
     EduCourse course = (EduCourse) dict.valueForKey("minusCourse");
     if (course != null) {
       Teacher teacher = (Teacher) dict.valueForKey("minusTeacher");
       if (teacher != null) export.addValue(Person.Utility.fullName(teacher, true, 2, 1, 1));
       else export.addValue(ses.valueForKeyPath("strings.RujelBase_Base.vacant"));
       if (course.comment() == null) {
         export.addValue(course.cycle().subject());
       } else {
         buf.delete(0, buf.length());
         buf.append(course.cycle().subject());
         buf.append(' ').append('(').append(course.comment()).append(')');
         export.addValue(buf.toString());
       }
     } else {
       export.addValue(null);
       export.addValue(null);
     }
     if (dict.valueForKey("eduGroup") != null)
       export.addValue(dict.valueForKeyPath("eduGroup.name"));
     else export.addValue(dict.valueForKey("grade"));
     export.addValue(dict.valueForKeyPath("reason.title"));
     export.addValue(dict.valueForKeyPath("reason.verification"));
     course = (EduCourse) dict.valueForKey("plusCourse");
     if (course != null) {
       Teacher teacher = (Teacher) dict.valueForKey("plusTeacher");
       export.addValue(Person.Utility.fullName(teacher, true, 2, 1, 1));
       if (course.comment() == null) {
         export.addValue(course.cycle().subject());
       } else {
         buf.delete(0, buf.length());
         buf.append(course.cycle().subject());
         buf.append(' ').append('(').append(course.comment()).append(')');
         export.addValue(buf.toString());
       }
     } else {
       export.addValue(null);
       export.addValue(null);
     }
     export.addValue(dict.valueForKey("value"));
   }
   return export;
 }
Beispiel #15
0
 public void appendTagAttributeToResponse(WOResponse response, String name, Object object) {
   if (object != null) {
     response._appendTagAttributeAndValue(name, object.toString(), true);
   }
 }
  public WOResponse _handleRequest(WORequest request) {
    // Retrieve the application object. We need to inform it of awake/sleep
    // and use some of its helper methods.
    WOApplication application = Application.app();

    WOResponse response;
    WOContext context;

    application.awake();
    try {
      // Instantiate the action object for this request.
      // The WOAction sets up the context and restores the session and so
      // on.
      WOAction action = new ContentAction(request);

      // Retrieve the context object from the action.
      context = action.context();

      // Retrieve the content path. e.g. blog or blog/2009/10/10/foobar or
      // whatever.
      String contentPath = request.requestHandlerPath();

      // TODO: We probably could use some exception handling here.
      // 1. performActionNamed throws generating the WOActionResults
      // 2. performActionNamed returns null
      // 3. generateResponse throws
      // 4. generateResponse returns null (although we do kind of handle
      // this already).

      // Ask the action object to handle the request. Unlike normal action
      // objects the
      // ContentAction object takes a path instead of the first part of a
      // method name.
      WOActionResults actionResults = action.performActionNamed(contentPath);

      // Generate the response object.
      if (actionResults != null) response = actionResults.generateResponse();
      else response = null;

      // FIXME: When we do add error handling, do we or don't we save the
      // session in the
      // event of an error?
      if (context != null) {
        // Check the session in to the session store. Particularly
        // important if the
        // session store is out of process.
        application.saveSessionForContext(context);
      }
    } finally {
      // End of request.
      application.sleep();
    }

    // Ah, the joys of calling private APIs. For some reason both
    // WOActionRequestHandler
    // and WOComponentRequestHandler know about and call this method as
    // virtually the
    // last thing before returning the response. I am somewhat unclear as to
    // why this
    // method is private and why it isn't called by our caller instead of
    // within the
    // request handler.
    // It is imperative that this method be called because it generates HTTP
    // Set-Cookie
    // headers from the NSArray<WOCookie>. Without this no cookies will ever
    // function.
    if (response != null) response._finalizeInContext(context);

    return response;
  }
Beispiel #17
0
  @Override
  public void appendToResponse(WOResponse response, WOContext context) {

    WOComponent component = context.component();
    String idString = (String) id.valueInComponent(component);
    if (idString == null) {
      throw new RuntimeException("id binding evaluated to null");
    }

    // UL for tabs
    response.appendContentString("<ul");
    appendTagAttributeToResponse(response, "class", valueForBinding("class", component));
    appendTagAttributeToResponse(response, "id", idString);

    // Optional JavaScriplets
    if (onLoad != null) {
      appendTagAttributeToResponse(response, "onLoad", onLoad.valueInComponent(component));
    }
    if (onSelect != null) {
      appendTagAttributeToResponse(response, "onSelect", onSelect.valueInComponent(component));
    }

    response.appendContentString(">\n");

    String paneControlID = idString + "_panecontrol";
    String selectedTabClassName = stringValueForBinding("selectedPanelClassName", component);
    if (selectedTabClassName == null) {
      selectedTabClassName = "active";
    }
    for (MTAjaxTabbedPanelTab tab : tabs) {

      if (tab.isVisble(component)) {
        boolean isSelectedTab = tab.isSelected(context.component());
        String panelTabID = (String) tab.id().valueInComponent(component);
        String panelID = panelTabID + "_panel";
        response.appendContentString("  <li");
        if (isSelectedTab) {
          response.appendContentString(" class=\"");
          response.appendContentString(selectedTabClassName);
          response.appendContentString("\"");
        }
        response.appendContentString(">\n");
        response.appendContentString("<a ");

        // add the accesskey
        if (tab.accesskey() != null) {
          String accessKeyStr = tab.accesskey().valueInComponent(component).toString();
          appendTagAttributeToResponse(response, "accesskey", accessKeyStr);
        }

        appendTagAttributeToResponse(response, "href", "javascript:void(0)");
        appendTagAttributeToResponse(response, "rel", panelID);
        response.appendContentString("\">");
        response.appendContentString((String) tab.name().valueInComponent(component));
        response.appendContentString("</a>\n");
        response.appendContentString("</li>\n");
      }
    }

    response.appendContentString("</ul>\n");

    // UL for panes
    response.appendContentString("<ul class=\"ajaxTabbedPanelPanes\" ");
    appendTagAttributeToResponse(response, "id", paneControlID);
    response.appendContentString(">\n");
    // The tabs render themselves as panes
    if (content != null) {
      content.appendToResponse(response, context);
    }
    response.appendContentString("</ul>\n");
    super.appendToResponse(response, context);

    AjaxUtils.appendScriptHeader(response);
    response.appendContentString("window.addEvent('domready', function() {");
    response.appendContentString("\n\tvar ");
    response.appendContentString(safeID(context));
    response.appendContentString(" = new MTAjaxTabbedPanel({");
    response.appendContentString("tabbedPanelTabsContainer : ");
    response.appendContentString("'");
    response.appendContentString(idString);
    response.appendContentString("', ");
    response.appendContentString("tabbedPanelPanesContainer : ");
    response.appendContentString("'");
    response.appendContentString(paneControlID);
    response.appendContentString("'");
    if (!selectedTabClassName.equals("active")) {
      response.appendContentString(", ");
      response.appendContentString("selectedTabClassName : ");
      response.appendContentString("'");
      response.appendContentString(selectedTabClassName);
      response.appendContentString("'");
    }

    response.appendContentString("});");
    response.appendContentString("\n});");
    AjaxUtils.appendScriptFooter(response);
  }